1. Audience
This document assumes basic knowledge of TRex, and assumes that TRex is installed and configured. For information, see the manual, especially the material up to the Basic Usage section.
2. Emulation support
2.1. High level functionality
The objective is to implement client side L3 protocols i.e ARP, IPv6, ND, MLD, IGMP in order to simulate a scale of clients and servers. This project is not limited to client protocols, but it is a good start. The project provides a framework to implement and use client protocols.
The framework is fast enough for control plane protocols and will work with TRex server. Very fast L7 applications (on top of TCP/UDP) will run on TRex server. One single thread of TRex-EMU can achieve a high rate of client creation/teardown. Each of the aforementioned protocol is implemented as a plugin. These plugins are self contained and can signal events one to the other, or to the framework, using an event-bus. (e.g. DHCP signals that it has a new IPv6 address). The framework has an event driven architecture, this way it can scale. The framework also provides to a protocol plugin infrastructure, for example RPC, timers, packet parsers, simulation and more.
- The main properties
-
-
Fast client creation/teardown. ~3K/sec for one thread.
-
Number of active client/namespace is limited only by the memory on the server.
-
Packet per second (PPS) in the range of 3-5 MPPS.
-
Python 2.7/3.0 Client API exposed through JSON-RPC.
-
Interactive support - Integrated with the TRex console.
-
Modular design. Each plugin is self contained and can be tested on its own.
-
TRex-EMU supports the following protocols:
-
| Plug-in | Description |
|---|---|
ARP |
RFC 826 |
CDP |
Cisco Delivery Protocol |
DHCPv4 |
RFC 2131 Client & Server |
DHCPv6 |
RFC 8415 client side |
DNS |
Domain Name System, RFC 1034/1035 |
DOT1X |
EAP-MD5/EAP-MSCHAPv2 RFC 3748/2759, IEEE 802.1X-2001 |
ICMP |
RFC 777 |
IGMP |
IGMP v3/v2/v1 RFC3376 |
IPv6 |
IPv6 ND, RFC 4443, RFC 4861, RFC 4862 and MLD and MLDv2 RFC 3810 |
LLDP |
IEEE 802.1AB |
mDNS |
Multicast DNS, RFC 6762 |
Netflow |
Netflow v9, RFC 3954 and Netflow v10 (IPFix), RFC 7011 |
Transport |
User space TCP (based on BSD, converted to native golang) and UDP |
Cisco telemetry TDL |
Under tests simulate network device |
2.2. TRex Architecture with TRex-EMU
TRex-EMU can receive commands (RPC via JSON-RPC) from a Python client and send/receive packets via a ZMQ channel that connects it to the TRex server (RX core). Packets from the network (from a TRex server physical port) that match a filter (dynamic) are forwarded to the TRex-EMU process. Packets from the EMU process are packed into the ZMQ channel and sent directly to the TRex physical port.
2.3. Internal Emulation Server Architecture
Each TRex emulation process called thread can have a few Namespaces.
Each Namespace must have a unique tuple key, that is composed from {physical-port, dot1q, QinQ}. The namespace key could be extended to tunnels in the future.
Each Client can be associated with one Namespace.
Each Protocol Plugin can attach an opaque object at each level (thread, namespace, client) and run the protocol logic at that level. For example, DHCPv6 will be run mainly at the client level, while MLDv2 will run on a namespace context.
Different plugins and frameworks can communicate through an event bus. A plugin can register on a topic (Subscriber) and can send an event on a specific topic (Publisher) (e.g. DHCPv6 can send an event upon a change of a source IPv6).
Something to note in this model is that Clients can share information on the same Namespace, reducing multicast, broadcast and generally packet duplication.
The previous figure shows a shared IPv4 default gateway for many clients, which is resolved once and shared with all the respective clients. So ARP broadcast packets do not need to be duplicated for each client. In this example, if all the clients had the same default gateway 16.0.0.1, we will have only one entry in the ARP cache table and each client will have a pointer to it. This is an example on how scaling in the number of clients can be achieved.
2.4. EMU main objects
-
Thread: Includes a few namespaces on different physical ports.
-
Namespace: A separate network entity that can include a number of clients. Each namespace has a unique physical port, dot1q and QinQ tuple key.
-
Namespace key tuple: A tuple that serves as the key of the namespace, hence must be unique per namespace.
-
Client: Represents a separate network node in the namespace. For example a different laptop or server. Each node can have only one IPv4 source address, and a few IPv6 global and local IPv6 addresses.
-
Plugin: Implements a protocol logic or a tunnel logic. Could attach an opaque object to a thread, namespace and client object and use the framework API.
2.5. EMU Thread
This object handles the following entities:
-
RPC over JSON-RPC/ZMQ
-
Timer wheel
-
Event bus
-
ZMQ veth for TX/RX packets
-
Parser to dispatch packets to plugins
-
Manages a set of namespaces
-
Manages fast zero copy packet allocation (mbuf) - inspired by BSD
-
Counters engine
2.6. EMU Namespace
type CNSCtx struct { ThreadCtx *CThreadCtx PluginCtx *PluginCtx DefClientPlugs *MapJsonPlugs } type CNsInfo struct { Port uint16 `json:"vport" validate:"required"` Tci [2]uint16 `json:"tci"` Tpid [2]uint16 `json:"tpid"` ActiveClients uint64 `json:"active_clients"` PlugNames []string `json:"plug_names"` } type CTunnelDataJson struct { Vport uint16 `json:"vport"` Tpid [2]uint16 `json:"tpid"` Tci [2]uint16 `json:"tci"` Plugins *MapJsonPlugs `json:"plugs"` }
Properties:
-
Associated only with one thread
-
Manages a set of clients
-
Each namespace should have a tuple key, represented by
CTunnelDataJson, and a vector of containing the names of the plugins that can transmit in this tunnel. -
Information per namespace through
CNsInfo, which is composed from the tunnel key, active clients and plugin names.
2.7. EMU Client
// CClientDg default GW type CClientDg struct { IpdgResolved bool `json:"resolve"` // bool in case it is resolved IpdgMac MACKey `json:"rmac"` // default } //CClientIpv6Nd information learned from router type CClientIpv6Nd struct { MTU uint16 `json:"mtu"` // MTU in L3 1500 by default DgMac MACKey `json:"dgmac"` // router dg PrefixIpv6 Ipv6Key `json:"prefix"` PrefixLen uint8 `json:"prefix_len"` IPv6 Ipv6Key `json:"ipv6"` } type CClient struct { dlist DList // for adding into list Ns *CNSCtx // pointer to a namespace Ipv4 Ipv4Key // source ipv4 Maskv4 Ipv4Key // mask default 0xffffffff DgIpv4 Ipv4Key // default gateway for ipv4 Mac MACKey // immutable over lifetime of client MTU uint16 // MTU in L3 1500 by default DGW *CClientDg /* resolve by ARP */ Ipv6Router *CClientIpv6Nd Ipv6DGW *CClientDg /* resolve by ipv6 */ Ipv6 Ipv6Key // set the self ipv6 by user DgIpv6 Ipv6Key // default gateway if provided would be in highest priority Dhcpv6 Ipv6Key // the dhcpv6 ipv6, another ipv6 would be the one that was learned from the router Ipv6ForceDGW bool /* true in case we want to enforce default gateway MAC */ Ipv6ForcedgMac MACKey ForceDGW bool /* true in case we want to enforce default gateway MAC */ Ipv4ForcedgMac MACKey PluginCtx *PluginCtx } type CClientCmd struct { Mac MACKey `json:"mac" validate:"required"` // the key mac address Ipv4 Ipv4Key `json:"ipv4"` // source ipv4 DgIpv4 Ipv4Key `json:"ipv4_dg"` // default gateway MTU uint16 `json:"ipv4_mtu"` // ipv4 mtu Ipv6 Ipv6Key `json:"ipv6"` // source global ipv6 DgIpv6 Ipv6Key `json:"dg_ipv6"` // ipv6 default gateway Ipv6ForceDGW bool `json:"ipv6_force_dg"` // force static default gateway Ipv6ForcedgMac MACKey `json:"ipv6_force_mac"` // the mac of the forced default gateway ForceDGW bool `json:"ipv4_force_dg"` // forced ipv4 default gateway Ipv4ForcedgMac MACKey `json:"ipv4_force_mac"` // the MAC of the ipv4 forced default gateway Plugins *MapJsonPlugs `json:"plugs"` // list of plugins } type CClientCmds struct { Clients []CClientCmd `json:"clients" validate:"required"` } type CClientInfo struct { Mac MACKey `json:"mac"` Ipv4 Ipv4Key `json:"ipv4"` DgIpv4 Ipv4Key `json:"ipv4_dg"` MTU uint16 `json:"ipv4_mtu"` Ipv6Local Ipv6Key `json:"ipv6_local"` Ipv6Slaac Ipv6Key `json:"ipv6_slaac"` Ipv6 Ipv6Key `json:"ipv6"` DgIpv6 Ipv6Key `json:"dg_ipv6"` DhcpIpv6 Ipv6Key `json:"dhcp_ipv6"` Ipv6ForceDGW bool `json:"ipv6_force_dg"` Ipv6ForcedgMac MACKey `json:"ipv6_force_mac"` ForceDGW bool `json:"ipv4_force_dg"` Ipv4ForcedgMac MACKey `json:"ipv4_force_mac"` DGW *CClientDg `json:"dgw"` Ipv6Router *CClientIpv6Nd `json:"ipv6_router"` Ipv6DGW *CClientDg `json:"ipv6_dgw"` PlugNames []string `json:"plug_names"` }
-
Associated only with one namespace
-
CClientInfois the information retrieved for each client in an incoming RPC command-
CClientDgis the IPv4 and/or IPv6 resolved default gateway using IPv6 ND and/or ARP -
Ipv6Routeris the IPv6 router advertised information
-
-
CClientCmdis the JSON-RPC information to create a new client-
CClientCmd.Pluginsis a vector of plugins for associating protocols plugins with a client/namespace example
-
[{'arp':{'enable':True}},{'icmp':{}},'dhcp':{'keep_alive':120}].
In this example we enable arp,icmp and dhcp plugin for this client and we can provide a init configuration.
-
One important limitation is that the client does not have a routing table in the first version, only a default gateway. It was done for simplicity, because the main objective is to verify a router/switch under test.
-
However, clients in the same subnet can still communicate using the default gateway, as long as the default gateway has routing abilities. In the ping tutorial we show how to ping a client in the same namespace/subnet.
3. Getting Started Tutorials
The tutorials in this section demonstrate basic use cases of the TRex-EMU server.
3.1. Tutorial: Load TRex server, One Client with ARP/ICMP plugin
- Goal
-
Create one new client with one source IPv4 configuration and ping from the router. An ASR1K (Cisco IOS-XE) is used in the following tutorials and it is connected directly on a physical port (without a switch).
-
ASR1K
-
Port/Interface: (Ten1/0/0)
-
IPv4: 1.1.5.1
-
Subnet Mask: /24 (255.255.255.0)
-
-
TRex EMU
-
Port 0
-
IPv4: 1.1.5.2
-
Subnet Mask: /24 (255.255.255.0)
-
-
- Profile
This profile is a way to create a database (tree) of namespaces and clients in Python, and forward the tree to the EMU server via RPC commands. Let’s look into the sections of the profile.
class Prof1(): def __init__(self): self.def_ns_plugs = None #self.def_c_plugs = None #
def create_profile(self, ns_size, clients_size): ns_list = [] # create different namespace each time vport, tci, tpid = 0, [0, 0], [0x00, 0x00] for j in range(vport, ns_size + vport): ns_key = EMUNamespaceKey(vport = j, tci = tci, tpid = tpid) ns = EMUNamespaceObj(ns_key = ns_key, def_c_plugs = self.def_c_plugs) # create namespace mac = Mac('00:00:00:70:00:01') ipv4 = Ipv4('1.1.5.2') dg = Ipv4('1.1.5.1') # create a different client each time for i in range(clients_size): client = EMUClientObj(mac = mac[i].V(), # create clients ipv4 = ipv4[i].V(), ipv4_dg = dg.V(), plugs = {'arp': {}, 'icmp': {}, #
}, ) ns.add_clients(client) ns_list.append(ns) return EMUProfile(ns = ns_list, def_ns_plugs = self.def_ns_plugs)
| The default plugin configuration for all the namespaces attached to a thread, could be None. In case a namespace has a plugin configuration it will have priority over the default. | |
| The default plugin configuration for all the clients on the same namespace. In case a client has a plugin configuration it will have a priority over the default. | |
Override plugin configuration per client, only arp and icmp
|
| def_ns_plugs | EMUNamespaceObj.plugs | Result |
|---|---|---|
|
None |
|
None |
|
|
|
|
|
| EMUNamespaceObj.def_c_plugs | EMUClientObj.plugs | Result |
|---|---|---|
|
None |
|
None |
|
|
|
|
|
The ASR1K configuration
interface TenGigabitEthernet1/0/0 mac-address 0000.0001.0000 mtu 12500 ip address 1.1.5.1 255.255.255.0 load-interval 30 arp timeout 70
The profile will create one client with 1.1.5.2/24.
- Start TRex as a server
[bash]>sudo ./t-rex-64 -i -c 1 --software --emu
the --emu CLI argument will load ZMQ channel to TX/RX packets and will tell the script to load the TRex-EMU server.
- Start the Console with EMU support
-
Use the following command to start the console with EMU support. Note that the commands are relative to the version and commands can be removed and added throughout releases.
[bash]> ./trex-console --emu Using 'python3' as Python interpeter Connecting to RPC server on port:4501 [SUCCESS] Connecting to publisher server on port:4500 [SUCCESS] Acquiring ports [0, 1, 2, 3]: [SUCCESS] Server Info: Server version: v2.75 @ STL Server mode: Stateless Server CPU: 2 x Intel(R) Xeon(R) CPU E5-2650 0 @ 2.00GHz Ports count: 4 x 10Gbps @ 82599EB 10-Gigabit SFI/SFP+ Network Connection Connecting to RPC server on port:4510 [SUCCESS] <<< this is connected to the emu Loading plugin: emu [SUCCESS] -=TRex Console v3.0=- trex>help Emulation Commands: emu_arp_cmd_query - Arp cmd query command emu_arp_get_cfg - Arp get configuration command emu_arp_set_cfg - Arp set configuration command emu_arp_show_cache - Arp show cache command emu_arp_show_counters - Show arp counters data from arp table. emu_dhcp_show_counters - Show dhcp counters (per client). emu_dhcpv6_show_counters - Show dhcpv6 counters (per client). emu_icmp_show_counters - Show icmp counters (per client). emu_igmp_add_mc - IGMP add mc command emu_igmp_get_cfg - IGMP get configuration command emu_igmp_remove_mc - IGMP remove mc command emu_igmp_set_cfg - IGMP set configuration command emu_igmp_show_counters - Show IGMP counters data from igmp table. emu_igmp_show_mc - IGMP show mc command emu_ipv6_add_mld - IPV6 add mld command emu_ipv6_get_cfg - IPV6 get configuration command emu_ipv6_remove_mld - IPV6 remove mld command emu_ipv6_set_cfg - IPV6 set configuration command emu_ipv6_show_cache - IPV6 show cache command emu_ipv6_show_counters - Show IPV6 counters data from ipv6 table. emu_ipv6_show_mld - IPV6 show mld command emu_load_profile - Load a given profile to emu server emu_remove_profile - Remove current profile from emu server emu_show_all - Show all current namespaces & clients emu_show_client_info - Show client information emu_show_counters - Show counters data from ctx according to given tables. emu_show_mbuf - Show mbuf usage in a table. emu_show_ns_info - Show namespace information trex>
- Load profile
-
This shows how to load the previous Python profile from the console:
trex>portattr -a --prom on #Applying attributes on port(s) [0, 1, 2, 3]: [SUCCESS] trex>portattr -a --mult on Applying attributes on port(s) [0, 1, 2, 3]: [SUCCESS] trex>portattr -a Port Status port | 0 | 1 | ----------------+----------------------+----------------------+-- driver | net_ixgbe | net_ixgbe | description | 82599EB 10-Gigabit | 82599EB 10-Gigabit | link status | UP | UP | link speed | 10 Gb/s | 10 Gb/s | port status | IDLE | IDLE | promiscuous | on | on | multicast | on | on | flow ctrl | none | none | vxlan fs | - | - | -- | | | layer mode | Ethernet | Ethernet | src IPv4 | - | - | IPv6 | off | off | src MAC | 00:00:00:02:00:00 | 00:00:00:04:00:00 | --- | | | Destination | 00:00:00:01:00:00 | 00:00:00:03:00:00 | ARP Resolution | - | - | ---- | | | VLAN | - | - | ----- | | | PCI Address | 0000:03:00.0 | 0000:03:00.1 | NUMA Node | 0 | 0 | RX Filter Mode | hardware match | hardware match | RX Queueing | off | off | Grat ARP | off | off | ------ | | | trex>emu_load_profile -f emu/simple_ipv4.py -t --ns 1 --clients 1 #
Converting file to profile [SUCCESS] Converting profile took: 24.81 [ms] Removing old emu profile [SUCCESS] Sending emu profile [SUCCESS] Sending profile took: 524.78 [ms] 553.79 [ms] trex>emu_show_all #
Namespace #1 Information Port | Vlan tags | Tpids | #Plugins | #Clients -----+-----------+-------+----------+--------- 0 | - | - | - | 1 Clients Information MAC | IPv4 | DG-IPv4 | MTU | IPv6 | ------------------+---------+---------+------+------------+- 00:00:00:70:00:01 | 1.1.5.2 | 1.1.5.1 | 1500 | 1234::1000 | 560.78 [ms] trex>emu_show_client_info --mac 00:00:00:70:00:01 -p 0 --json #
{ "plug_names": [ "arp", "icmp" ], "dhcp_ipv6": "::", "mac": "00:00:00:70:00:01", "ipv4_force_dg": false, "ipv6_force_mac": "00:00:00:00:00:00", "dg_ipv6": "::", "ipv4_mtu": 1500, "ipv4_force_mac": "00:00:00:00:00:00", "ipv6_dgw": "None", "ipv6": "1234::1000", "ipv6_force_dg": false, "ipv4_dg": "1.1.5.1", "ipv6_local": "fe80::200:ff:fe70:1", "dgw": { "rmac": "00:00:00:00:00:00", "resolve": false }, "ipv6_router": "None", "ipv4": "1.1.5.2", "ipv6_slaac": "::" } 102.34 [ms] trex>emu_show_counters #
Ctx Counters name | value ---------+------ addNs | 1 activeNs | 1 Mbuf-Pool Counters name | value ---------------+------ mbufAlloc | 2 mbufAllocCache | 10 mbufFreeCache | 12 Timerw Counters name | value ------------+------- activeTimer | 2 ticks | 146226 Mbuf-128 Counters name | value ---------------+------ mbufAlloc | 2 mbufAllocCache | 10 mbufFreeCache | 12 Veth Counters name | value ---------+------ TxPkts | 12 TxBytes | 504 TxBatch* | 11 248.72 [ms] trex>emu_show_mbuf #
Mbuf Util Sizes: | 128b | 256b | 512b | 1k | 2k | 4k | 9k ------------------+-------+-------+-------+-------+-------+-------+--- Allocations | 2 | 0 | 0 | 0 | 0 | 0 | 0 Free | 0 | 0 | 0 | 0 | 0 | 0 | 0 Cache Allocations | 11 | 0 | 0 | 0 | 0 | 0 | 0 Cache Free | 13 | 0 | 0 | 0 | 0 | 0 | 0 Hit Rate | 84% | 0% | 0% | 0% | 0% | 0% | 0% Actives | 26 | 0 | 0 | 0 | 0 | 0 | 0 123.68 [ms] trex>emu_show_ns_info -p 0 #
Namespace Information Port | Vlan tags | Tpids | #Plugins | #Clients -----+-----------+-------+----------+--------- 0 | - | - | - | 1 108.65 [ms]
| Promiscuous mode and multicast should be turned on to forward the broadcast and multicast packets that relate to TRex-EMU. | |
emu_load_profile removes the old profile if it exists and loads the new profile using SDK API. You can specify the rate of new clients and rate or removal.
Emu profiles have their own argparser, if you wish to see profile’s tunables run:
emu_load_profile -f emu/simple_emu.py -t --help
| |
emu_show_all : shows all the clients
| |
emu_show_client_info : shows the client parameters
| |
emu_show_counters : shows the framework counters for all engines
| |
emu_show_mbuf : shows the framework packets buffers
| |
emu_show_ns_info: shows info per namespace
|
|
|
In order to make that separation between load_profile flags and profile tuneables, -t MUST be at the end.i.e: emu_load_profile -f emu/simple_emu.py --max 100 -t --ns 1 --clients 10 // Good. emu_load_profile -f emu/simple_emu.py -t --ns 1 --clients 10 --max 100 // Bad, "max" flag is not a profile tuneable. |
To show counters per plugin info use emu_xxx_show_counters where xxx is the plugin name. In this case let’s try ARP:
trex>emu_arp_show_counters -p 0 #Arp Counters #
name | value ---------------------+------ timerEventIncomplete | 43 addIncomplete | 1 pktTxArpQuery | 54 pktTxGArp | 1 tblActive | 1 tblAdd | 1 associateWithClient | 1
emu_arp_show_counters works per namespace so you should provide port and tunnel (if exists).
| |
The counters are global for all the clients in the same namespace as they share the ARP cache table.
|
csi-mcp-asr1k-40> show ip arp Protocol Address Age (min) Hardware Addr Type Interface Internet 1.1.5.1 - 0000.0001.0000 ARPA TenGigabitEthernet1/0/0 Internet 1.1.5.2 0 0000.0070.0001 ARPA TenGigabitEthernet1/0/0 Internet 1.1.6.1 - 0000.0003.0000 ARPA TenGigabitEthernet1/1/0 Internet 1.1.7.1 - 0000.0005.0000 ARPA TenGigabitEthernet1/2/0 Internet 1.1.8.1 - 0000.0007.0000 ARPA TenGigabitEthernet1/3/0 csi-mcp-asr1k-40> ping 1.1.5.2 Type escape sequence to abort. Sending 5, 100-byte ICMP Echos to 1.1.5.2, timeout is 2 seconds: !!!!! Success rate is 100 percent (5/5), round-trip min/avg/max = 62/70/80 ms csi-mcp-asr1k-40
The router succesfully idetified the client in the ARP table and it is possible to ping to it from the router.
Now you can try with 10,000 clients.
trex>emu_load_profile -f emu/simple_ipv4.py -t --ns 1 --clients 10000
|
|
You will need to change the interface mask from 255.255.255.0 to 255.255.0.0, from /24 to /16. |
3.2. Tutorial: Ping
Needless to say, ping is the most basic utility in terms of verifying network connections. However, it can be used for benchmarking and for gathering data, such as latency. The TRex Emu server offers the ping functionality both for ICMPv4 and ICMPv6. In this tutorial we will explore this functionality and learn the basics of how to use.
3.2.1. ICMPv4
We have the following ICMP command available in the console. (And a few more in the API)
emu_icmp_ping - ICMP ping utility (per client).
In order to be able to use the ping, first let us understand the setup by looking at the following figure:
The ASR1K is connected on port Te0/0/0 to all the clients we will emulate. On this interface we defined 1.1.1.1/24. The next hop of the router is 1.1.1.2. All the clients we will emulate, will start from 1.1.1.3 and their default gateway will be the router, meaning 1.1.1.1
Let us load the profile which will emulate the clients as mentioned.
trex>emu_load_profile -f emu/simple_icmp.py -t --ns 1 --clients 3
We can verify the setup by:
trex>emu_show_all Namespace #1 Information Port | Vlan tags | Tpids | Plugins | #Clients -----+-----------+-------+-----------+--------- 0 | - | - | arp, icmp | 3 Clients Information MAC | IPv4 | DG-IPv4 | MTU | Plugins ------------------+---------+---------+------+---------- 00:00:00:70:00:03 | 1.1.1.3 | 1.1.1.1 | 1500 | arp, icmp 00:00:00:70:00:04 | 1.1.1.4 | 1.1.1.1 | 1500 | arp, icmp 00:00:00:70:00:05 | 1.1.1.5 | 1.1.1.1 | 1500 | arp, icmp
Let’s dive into it:
trex>emu_icmp_ping -p 0 --mac 00:00:00:70:00:03 Starting to ping : [SUCCESS] Progress: 100.00%, Sent: 5/5, Rcv: 5/5, Err: 0/5, RTT min/avg/max = 0.96/3.58/11.52 ms Completed
Pay attention that we didn’t write any parameters into the ping, so it used the default parameters, which go as follows:
-
amount- how many echo requests to send, default value is 5 -
pace- how many packets per second (pps) to send, default value is 1 -
dst- destination IPv4, default value is Default Gateway -
size- size of the ICMP payload in bytes, default and minimal is 16 bytes.
|
|
You can stop pinging by sending a Keyboard Interrupt with Ctrl+C. |
Let us see the statistics of the ICMP plugin:
trex>emu_icmp_show_counters -p 0 Icmp Counters name | value ------------------+------ pktTxIcmpQuery | 5 pktRxIcmpResponse | 5
If we run the Emulator with the -m flag we can actually capture the pcap and see the packets:
Pay attention to the timing being 1 second between each Echo Request.
Let us try to ping another client:
trex>emu_icmp_ping -p 0 --mac 00:00:00:70:00:03 --dst 1.1.1.4 --amount 3 --size 100 Starting to ping : [SUCCESS] Progress: 100.00%, Sent: 3/3, Rcv: 3/3, Err: 0/3, RTT min/avg/max = 3.70/10.20/22.66 ms Completed
Pinging works and we get replies from the other client, however this doesn’t work as you would normally think it would work.
We already mentioned, that the clients have simply a default gateway, and they can’t resolve clients in the same subnet.
Hence, when pinging, the next hop will always be the default gateway (in our case the router), also when the clients are in the same subnet.
From the router the Echo Request packet will be forwarded to the destination, and then from the destination back to the router.
Let us look at a capture for complete information.
Looking at the TTL we can see that the router decreases it twice, once in every direction.
Lastly, let us look at the case in which we have errors. Let us try and ping a unreachable client.
trex>emu_icmp_ping -p 0 --mac 00:00:00:70:00:03 --dst 1.1.3.1 --amount 3 Starting to ping : [SUCCESS] Progress: 100.00%, Sent: 3/3, Rcv: 0/3, Err: 3/3, RTT min/avg/max = 0.00/0.00/0.00 ms Completed
The error counter sums the following errors:
-
replies out of order
-
replies with malformed packet
-
replies with invalid latency
-
replies with bad ICMPv4 identifier
-
destination unreachable
For precise counters and more options you can use the API.
However, we can see the destination unreachable packets in the global ICMP counters:
trex>emu_icmp_show_counters -p 0 Icmp Counters name | value ------------------------+------ pktTxIcmpQuery | 3 pktRxIcmpDstUnreachable | 3
|
|
When pinging at high rates you might note that error counter is low. This happens because we finish when the client sends it’s last Echo Request, however for destination unreachable like errors the replies arrive late. |
3.2.2. ICMPv6
We tried to make the pinging utilities for ICMPv4 and ICMPv6 as alike as possible.
In order to ping using ICMPv6 one must use the following command:
emu_ipv6_ping - ICMPv6 ping utility (per client).
Let us load an IPv6 profile which will simulate some IPv6 clients:
trex>emu_load_profile -f emu/simple_ipv6.py -t --ns 1 --clients 3
We will focus on the first client:
trex>emu_show_client_info -p 0 --mac 00:00:00:70:00:01 --json { "ipv4_dg": "0.0.0.0", "ipv6_dgw": null, "dhcp_ipv6": "::", "ipv6_slaac": "2001:db8:0:2222:200:ff:fe70:1", "ipv4_force_mac": "00:00:00:00:00:00", "ipv6_force_mac": "00:00:00:00:00:00", "ipv6_router": { "dgmac": "00:00:00:01:00:02", "prefix": "2001:db8:0:2222::", "ipv6": "fe80::200:ff:fe01:2", "prefix_len": 64, "mtu": 9050 }, "plug_names": "ipv6", "ipv4_force_dg": false, "ipv4_mtu": 1500, "mac": "00:00:00:70:00:01", "ipv4": "0.0.0.0", "dg_ipv6": "::", "ipv6": "2001:db8:1::2", "ipv6_force_dg": false, "ipv6_local": "fe80::200:ff:fe70:1", "dgw": null }
Also we can see the addresses that the Router has:
asr1001-01> show ipv6 interface br | e down Te0/0/0 [up/up] FE80::200:FF:FE01:2 2001:DB8:0:2222::1 Te0/0/1 [up/up] FE80::200:FF:FE02:2 2001:DB8:1:2222::1
Our clients are directly connected to Te0/0/0.
Let us start with a simple ping:
trex>emu_ipv6_ping -p 0 --mac 00:00:00:70:00:01 Starting to ping : [SUCCESS] Progress: 100.00%, Sent: 5/5, Rcv: 0/5, Err: 0/5, RTT min/avg/max = 0.00/0.00/0.00 ms Completed
We tried to ping our default gateway and got no response. In the following analysis we will understand why:
Firstly, what is our default gateway? The default gateway IPv6 is resolved in the following order:
-
dg_ipv6 -
ipv6_router.ipv6
Meaning, an explicitly set default gateway will take priority over a Router Advertisement (RA).
Since the dg_ipv6 is unset we actually tried to ping the address received from the RA, fe80::200:ff:fe01:2.
Next let us try to understand what is the source IPv6 we used. The source IPv6 is resolved in the following order:
-
dhcp_ipv6 -
ipv6 -
ipv6_slaac
Meaning, top priority is given to an DHCPv6 assigned address, then to an explicitly set IPv6 and lastly to the SLAAC resolved IPv6.
In our case the dhcp_ipv6 is unset, and as such we will try to ping using 2001:db8:1::2 as a source address.
Let us see if the router knows our address:
asr1001-01>show ipv6 route IPv6 Routing Table - default - 5 entries Codes: C - Connected, L - Local, S - Static, U - Per-user Static route B - BGP, R - RIP, H - NHRP, I1 - ISIS L1 I2 - ISIS L2, IA - ISIS interarea, IS - ISIS summary, D - EIGRP EX - EIGRP external, ND - ND Default, NDp - ND Prefix, DCE - Destination NDr - Redirect, O - OSPF Intra, OI - OSPF Inter, OE1 - OSPF ext 1 OE2 - OSPF ext 2, ON1 - OSPF NSSA ext 1, ON2 - OSPF NSSA ext 2 la - LISP alt, lr - LISP site-registrations, ld - LISP dyn-eid a - Application C 2001:DB8:0:2222::/64 [0/0] via TenGigabitEthernet0/0/0, directly connected L 2001:DB8:0:2222::1/128 [0/0] via TenGigabitEthernet0/0/0, receive C 2001:DB8:1:2222::/64 [0/0] via TenGigabitEthernet0/0/1, directly connected L 2001:DB8:1:2222::1/128 [0/0] via TenGigabitEthernet0/0/1, receive L FF00::/8 [0/0] via Null0, receive
We see that indeed the router doesn’t know this address, hence it won’t reply.
From here we have to options:
Option 1:
We can use a source address that the router knows, for example the local link IPv6 of the client, or the SLAAC IPv6,
trex>emu_ipv6_ping -p 0 --mac 00:00:00:70:00:01 --src fe80::200:ff:fe70:1 Starting to ping : [SUCCESS] Progress: 100.00%, Sent: 5/5, Rcv: 5/5, Err: 0/5, RTT min/avg/max = 0.98/10.25/44.83 ms Completed
|
|
You can use only addresses you own as source IPv6. |
Option 2:
We will add a static route in the router to the ipv6 of the clients we generated, in the following way:
asr1001-01(config)>ipv6 route 2001:db8:1::0/112 Te0/0/0
We can verify we have the route:
asr1001-01>show ipv6 route 2001:db8:1::2 Routing entry for 2001:DB8:1::/112 Known via "static", distance 1, metric 0 Route count is 1/1, share count 0 Routing paths: directly connected via TenGigabitEthernet0/0/0 Last updated 00:01:07 ago
Now we can retry:
trex>emu_ipv6_ping -p 0 --mac 00:00:00:70:00:01 Starting to ping : [SUCCESS] Progress: 100.00%, Sent: 5/5, Rcv: 5/5, Err: 0/5, RTT min/avg/max = 1.28/10.84/45.49 ms Completed
We are successful, let us validate with the capture:
Lastly, we can ping the global address of the router with some address we own, for example the SLAAC address:
trex>emu_ipv6_ping -p 0 --mac 00:00:00:70:00:01 --src 2001:db8:0:2222:200:ff:fe70:1 --dst 2001:DB8:0:2222::1 --pace 2000 --amount 10000 Starting to ping : [SUCCESS] Progress: 100.00%, Sent: 10000/10000, Rcv: 10000/10000, Err: 0/10000, RTT min/avg/max = 1.23/3.10/6.30 ms Completed
We can see the ping counters using the global IPv6 counters:
trex>emu_ipv6_show_counters -p 0 --tables ping Pingv6 Counters name | value ------------------+------ pktTxIcmpQuery | 10000 pktRxIcmpResponse | 10000
3.3. Tutorial: IGMPv2/v3
- Goal
-
Add a few clients and some multicast address
TRex supports IGMPv2/v3 (RFC3376) and can maintain (add/remove) scale of multicast IPs. For IGMPv3 it supports (s,g) filter using add (s,g) and remove (s,g)
class Prof1(): def __init__(self): self.mac = Mac('00:00:00:70:00:01') #self.def_ns_plugs = {'igmp' : {'dmac':self.mac.V()}} self.def_c_plugs = None def create_profile(self, ns_size, clients_size): ns_list = [] # create different namespace each time vport, tci, tpid = 0, [0, 0], [0x00, 0x00] for j in range(vport, ns_size + vport): ns_key = EMUNamespaceKey(vport = j, tci = tci, tpid = tpid) ns = EMUNamespaceObj(ns_key = ns_key, def_c_plugs = self.def_c_plugs) mac = self.mac ipv4 = Ipv4('1.1.5.2') dg = Ipv4('1.1.5.1') # create a different client each time for i in range(clients_size): client = EMUClientObj(mac = mac[i].V(), ipv4 = ipv4[i].V(), ipv4_dg = dg.V(), plugs = {'arp': {}, 'icmp': {}, 'igmp': {}, #
}, ) ns.add_clients(client) ns_list.append(ns) return EMUProfile(ns = ns_list, def_ns_plugs = self.def_ns_plugs)
self.def_ns_plugs = {'igmp' : {'dmac':[0,0,0,0x70,0,1]}} is the init JSON for the IGMP plugin. The plugin works on a namespace level (not client level) but there is need for at least one designator client.
This client will represent the multicast groups for all the clients on the same namespace.
In this example we took the first client MAC (00:00:00:70:00:01).
| |
IGMP plugin should be enabled in the client plugs parameter (EMUClientObj)
|
trex>portattr -a --prom on
trex>emu_load_profile -f emu/simple_igmp.py -t --ns 1 --clients 10
trex>emu_igmp_add_mc -p 0 --4 227.0.1.1 --4 -count 10 #
124.90 [ms]
trex>emu_igmp_show_mc -p 0 #
Current mc:
227.0.1.1
227.0.1.2
227.0.1.3
227.0.1.4
227.0.1.5
227.0.1.6
227.0.1.7
227.0.1.8
227.0.1.9
227.0.1.10
227.0.1.11
trex>emu_igmp_get_cfg -p 0
Plugin "Igmp" Cfg:
mtu | dmac | version
-----+-------------------+--------
1500 | 00:00:00:70:00:01 | 3 #
| Add 227.0.1.1 to 227.0.1.11 multicast addresses (count is 10) | |
The table could be seen using emu_igmp_show_mc
| |
The IGMP packets will be sent from client 00:00:00:70:00:01
|
ip igmp limit 1000 << ip multicast-routing distributed << interface TenGigabitEthernet1/0/0 mac-address 0000.0001.0000 mtu 9050 ip address 1.1.5.1 255.255.255.0 ip pim sparse-dense-mode << ip igmp version 3 << ip igmp query-interval 10 << load-interval 30
>show ip igmp groups IGMP Connected Group Membership Group Address Interface Uptime Expires Last Reporter 227.0.1.1 TenGigabitEthernet1/0/0 00:00:28 00:00:29 1.1.5.2 227.0.1.2 TenGigabitEthernet1/0/0 00:00:28 00:00:29 1.1.5.2 227.0.1.3 TenGigabitEthernet1/0/0 00:00:28 00:00:29 1.1.5.2 227.0.1.4 TenGigabitEthernet1/0/0 00:00:28 00:00:29 1.1.5.2 227.0.1.5 TenGigabitEthernet1/0/0 00:00:28 00:00:29 1.1.5.2 227.0.1.6 TenGigabitEthernet1/0/0 00:00:28 00:00:29 1.1.5.2 227.0.1.7 TenGigabitEthernet1/0/0 00:00:28 00:00:29 1.1.5.2 227.0.1.8 TenGigabitEthernet1/0/0 00:00:28 00:00:29 1.1.5.2 227.0.1.9 TenGigabitEthernet1/0/0 00:00:28 00:00:29 1.1.5.2 227.0.1.10 TenGigabitEthernet1/0/0 00:00:28 00:00:29 1.1.5.2 227.0.1.11 TenGigabitEthernet1/0/0 00:00:28 00:00:29 1.1.5.2 224.0.1.40 TenGigabitEthernet1/0/0 1w0d 00:00:22 1.1.5.1
trex>emu_igmp_add_mc_sg --4g 239.0.0.1 --4s 10.0.0.1 -p 0 trex>emu_igmp_add_mc_sg --4g 239.0.0.1 --4s 10.0.0.2 -p 0 trex>emu_igmp_add_mc_sg --4g 239.0.0.1 --4s 10.0.0.3 -p 0
>show ip igmp groups 239.0.0.1 detail Flags: L - Local, U - User, SG - Static Group, VG - Virtual Group, SS - Static Source, VS - Virtual Source, Ac - Group accounted towards access control limit Interface: TenGigabitEthernet1/0/0 Group: 239.0.0.1 Flags: Ac Uptime: 00:01:38 Group mode: INCLUDE << Last reporter: 1.1.5.2 Group source list: (C - Cisco Src Report, U - URD, R - Remote, S - Static, V - Virtual, M - SSM Mapping, L - Local, Ac - Channel accounted towards access control limit) Source Address Uptime v3 Exp CSR Exp Fwd Flags 10.0.0.1 00:01:38 00:01:27 stopped Yes R 10.0.0.2 00:01:38 00:01:27 stopped Yes R 10.0.0.3 00:01:38 00:01:27 stopped Yes R
3.4. Tutorial: DHCPv4
3.4.1. DHCPv4 Client
- Goal
-
Add clients that interact with DHCP server to get the IPv4/Default gateway
class Prof1(): def __init__(self): self.mac = Mac('00:00:00:70:00:01') self.def_ns_plugs = {'igmp' : {'dmac':self.mac.V()}} self.def_c_plugs = None def create_profile(self, ns_size, clients_size): ns_list = [] # create different namespace each time vport, tci, tpid = 0, [0, 0], [0x00, 0x00] for j in range(vport, ns_size + vport): ns_key = EMUNamespaceKey(vport = j, tci = tci, tpid = tpid) ns = EMUNamespaceObj(ns_key = ns_key, def_c_plugs = self.def_c_plugs) mac = self.mac ipv4 = Ipv4('0.0.0.0') dg = Ipv4('0.0.0.0') ## create a different client each time for i in range(clients_size): client = EMUClientObj(mac = mac[i].V(), ipv4 = ipv4.V(), #
ipv4_dg = dg.V(), plugs = {'arp': {}, 'icmp': {}, 'igmp': {}, #
'dhcp': {} }, ) ns.add_clients(client) ns_list.append(ns) return EMUProfile(ns = ns_list, def_ns_plugs = self.def_ns_plugs)
Add dhcp to the client plugin
| |
| Change IPv4/DG to 0.0.0.0 | |
Change ipv4_inc to 0 as DHCP will change the IP
|
Now each client will request the IPv4/Default gateway from the DHCP server and signal to ARP/ICMP with the new IPv4 source address and default gateway.
- ASR1K configuration
-
We can configure a DHCP Pool in the router:
ip dhcp pool 1 network 1.1.5.0 255.255.255.0 domain-name cisco.com dns-server 172.16.1.103 172.16.2.10 lease 30
trex>emu_load_profile -f emu/simple_dhcp.py -t --ns 1 --clients 10 #Converting file to profile 10 [SUCCESS] Converting profile took: 34.62 [ms] Removing old emu profile [SUCCESS] Sending emu profile [SUCCESS] Sending profile took: 2.13 [sec] 2.17 [sec] trex>emu_show_all Namespace #1 Information Port | Vlan tags | Tpids | #Plugins | #Clients -----+-----------+-------+----------+--------- 0 | - | - | - | 10 Clients Information MAC | IPv4 | DG-IPv4 | MTU | IPv6 ------------------+----------+---------+------+---------------------+ 00:00:00:70:00:01 | 1.1.5.22 | 1.1.5.1 | 1500 | fe80::200:ff:fe70:1 | 00:00:00:70:00:02 | 1.1.5.72 | 1.1.5.1 | 1500 | fe80::200:ff:fe70:2 | 00:00:00:70:00:03 | 1.1.5.73 | 1.1.5.1 | 1500 | fe80::200:ff:fe70:3 | 00:00:00:70:00:04 | 1.1.5.70 | 1.1.5.1 | 1500 | fe80::200:ff:fe70:4 | 00:00:00:70:00:05 | 1.1.5.71 | 1.1.5.1 | 1500 | fe80::200:ff:fe70:5 | 00:00:00:70:00:06 | 1.1.5.68 | 1.1.5.1 | 1500 | fe80::200:ff:fe70:6 | 00:00:00:70:00:07 | 1.1.5.69 | 1.1.5.1 | 1500 | fe80::200:ff:fe70:7 | 00:00:00:70:00:08 | 1.1.5.66 | 1.1.5.1 | 1500 | fe80::200:ff:fe70:8 | 00:00:00:70:00:09 | 1.1.5.67 | 1.1.5.1 | 1500 | fe80::200:ff:fe70:9 | 00:00:00:70:00:0a | 1.1.5.89 | 1.1.5.1 | 1500 | fe80::200:ff:fe70:a | 990.49 [ms] trex> trex>emu_dhcp_show_counters -p 0 --mac 00:00:00:70:00:01 #
Dhcp Counters name | value --------------+------ pktTxDiscover | 1 pktRxOffer | 1 pktTxRequest | 1 pktRxAck | 1 pktRxNotify | 1 229.34 [ms]
Load the dhcp profile
| |
The dhcp plugin works per client, so the MAC should be provided to get the counters
|
>show ip dhcp server statistics Memory usage 65910 Address pools 1 Database agents 0 Automatic bindings 100 Manual bindings 0 Expired bindings 0 Malformed messages 0 Secure arp entries 0 Renew messages 0 Workspace timeouts 0 Static routes 0 Relay bindings 0 Relay bindings active 0 Relay bindings terminated 0 Relay bindings selecting 0 Message Received BOOTREQUEST 0 DHCPDISCOVER 302272 DHCPREQUEST 211 DHCPDECLINE 0 DHCPRELEASE 125 DHCPINFORM 0 DHCPVENDOR 0 BOOTREPLY 0 DHCPOFFER 0 DHCPACK 0 DHCPNAK 0 Message Sent BOOTREPLY 0 DHCPOFFER 211 DHCPACK 211 DHCPNAK 0 Message Forwarded BOOTREQUEST 0 DHCPDISCOVER 0 DHCPREQUEST 0 DHCPDECLINE 0 DHCPRELEASE 0 DHCPINFORM 0 DHCPVENDOR 0 BOOTREPLY 0 DHCPOFFER 0 DHCPACK 0 DHCPNAK 0 DHCP-DPM Statistics Offer notifications sent 0 Offer callbacks received 0 Classname requests sent 0 Classname callbacks received 0
3.4.2. DHCPv4 Server
TRex Emu supports DHCPv4 Server too. This is done in a separate plugin from the DHCPv4 Client. The DHCPv4 Server implementation is based on RFC 2131 and has some minor limitations such as:
-
Supports only Ethernet as Hardware Type
-
Supports only chaddr as a Client Identifier.
-
Only one DHCP Server is supported per subnet.
-
No data cached for client’s whose lease finished.
The server supports all of the following messages:
-
DHCPDISCOVER
-
DHCPREQUEST
-
DHCPDECLINE
-
DHCPRELEASE
-
DHCPINFORM
|
|
DHCPDECLINE can be used as a tool to exhaust the pool of available addresses and exploit a Denial of Service attack. Use with care! |
-
The server can be specified a default lease time to provide its clients with. It can also be provided with a minimal and maximal possible lease time so that clients requesting a specific lease time can be granted that lease iff the requested lease time is within the bounds of minimal and maximal possible lease.
-
The server supports multiple pools/scopes. Each pool is represented by a range [min-max] and a subnet mask given as a prefix. Also, we can specify a list of IPv4 to exclude from the pool in case of static addresses or addresses already in use by the default gateway.
|
|
Two different pools cannot be in the same subnet. If two pools share the same subnet, with the current implementation we will always offer an IP from the first pool in the list. |
|
|
No need to worry about Network Id and Broadcast Id addresses, the implementation handles it by skipping these addresses. |
-
Lastly, the server can be provided with a list of options for each type of response it sends. Note however that you mustn’t provide options that are forbidden for that type of response.
-
DHCPOFFER
-
DHCPACK
-
DHCPNAK
-
A configuration of a DHCPv4 Server looks like this:
{ "default_lease": 120,"minimal_lease": 20,
"maximal_lease": 300,
"next_server_ip": "1.1.1.2"
"pools": [
{ "min": "1.1.2.0", "max": "1.1.2.255", "prefix": 24, "exclude": ["1.1.2.1", "1.1.2.2"]
}, { "min": "1.1.100.0", "max": "1.1.100.255", "prefix": 24, "exclude": ["1.1.100.1"] }, { "min": "1.1.200.2", "max": "1.1.200.255", "prefix": 24, } ], "options": { "offer": [
{ "type": 6, # DNS Server "data": [8, 8, 8, 8] # 8.8.8.8 }, { "type": 15, # Domain Name "data": [99, 105, 115, 99, 111, 46, 99, 111, 109] # cisco.com } ], "ack": [ { "type": 6, "data": [8, 8, 8, 8] }, { "type": 15, "data": [99, 105, 115, 99, 111, 46, 99, 111, 109] } ] } }
| Default lease time in seconds offered to client. | |
| Minimal lease time in seconds requested by the client that the server is willing to accept. | |
| Maximal lease time in seconds requested by the client that the server is willing to accept. | |
| Next Server IPv4 in case it exists. | |
| List of pools/scopes. | |
| Excluded values from that pool, for example can be static addresses. | |
| List of options to send with every response message. This is added to the list of the mandatory options that the server must be provide. |
|
|
For an updated and complete version of the fields refer to the SDK. |
We will show two use cases.
-
The first one uses an ASR1K router as a DHCP Relay.
-
The second one uses the [Proxy].
DHCPv4 Server with Relay
In this first example, we will use the emu/dhcpsrv_relay.py profile. Our ASR1K has two interfaces, as shown below.
show ip interface brief Interface IP-Address OK? Method Status Protocol Te0/0/0 1.1.1.1 YES unset up up Te0/0/1 1.1.2.1 YES unset up up
In our profile, we will emulate the DHCPv4 Server behind Te0/0/0. We will emulate the DHCPv4 Clients behind Te0/0/1.
We can configure the Te0/0/1 interface as a DHCPv4 Relay Server using the following command:
> int Te0/0/1 > ip helper-address 1.1.1.3
|
|
The default address for the DHCPv4 Server in the profile is 1.1.1.3 but you can control it using the tunables. |
We start by loading the profile using:
trex(service-filtered)>emu_load_profile -f emu/dhcpsrv_relay.py -t -h usage: trex_console.py [-h] [--clients CLIENTS] [--mac MAC] [--srv_ip SRV_IP] [--srv_dg_ip SRV_DG_IP] Argparser for DHCP Relay. Port 0 - Srv. Port 1 - Clients optional arguments: -h, --help show this help message and exit --clients CLIENTS Number of clients to create. (default: 3) #--mac MAC Starting MAC address (default: 00:00:00:70:00:01) #
--srv_ip SRV_IP Server IPv4 (default: 1.1.1.3) #
--srv_dg_ip SRV_DG_IP Server Default Gateway (default: 1.1.1.1) #
32.25 [ms] trex(service-filtered)>emu_load_profile -f emu/dhcpsrv_relay.py -t --clients 250 #
| Specify the number of DHCPv4 Clients to emulate. | |
| Specify the starting MAC address. | |
| Specify the IP address of the DHCPv4 Server. | |
| Specify the Default Gateway for the DHCPv4 Server. | |
| Load the profile with 250 DHCPv4 Clients. |
Next we can see the counters of any DHCPv4 Client:
trex(service-filtered)>emu_dhcp_show_counters -p 1 --mac 00:00:00:70:00:02 Dhcp Counters name | value --------------+------ pktTxDiscover | 1 pktRxOffer | 1 pktTxRequest | 1 pktRxAck | 1 pktRxNotify | 1 14.58 [ms]
We can see the counters of the DHCPv4 Server:
trex(service-filtered)>emu_dhcpsrv_show_counters -p 0 --mac 00:00:00:70:00:01 Dhcpsrv Counters name | value --------------+------ activeClients | 250 pktRx | 500 pktRxDiscover | 250 pktRxRequest | 250 pktTx | 500 pktTxOffer | 250 pktTxAck | 250 13.91 [ms]
Lastly, we can see that the clients received IPv4 addresses and Default Gateways:
trex(service-filtered)> trex(service-filtered)>emu_show_all Namespace #1 Information Port | Vlan tags | Tpids | Plugins | #Clients -----+-----------+-------+--------------------+--------- 0 | - | - | arp, dhcpsrv, icmp | 1 Clients Information MAC | IPv4 | DG-IPv4 | MTU | Plugins ------------------+---------+---------+------+------------------- 00:00:00:70:00:01 | 1.1.1.3 | 1.1.1.1 | 1500 | arp, dhcpsrv, icmp Press Enter to see more namespaces Namespace #2 Information Port | Vlan tags | Tpids | Plugins | #Clients -----+-----------+-------+-----------------+--------- 1 | - | - | arp, dhcp, icmp | 250 Clients Information MAC | IPv4 | DG-IPv4 | MTU | Plugins ------------------+----------+---------+------+---------------- 00:00:00:70:00:02 | 1.1.2.3 | 1.1.2.1 | 1500 | arp, dhcp, icmp 00:00:00:70:00:03 | 1.1.2.4 | 1.1.2.1 | 1500 | arp, dhcp, icmp 00:00:00:70:00:04 | 1.1.2.5 | 1.1.2.1 | 1500 | arp, dhcp, icmp 00:00:00:70:00:05 | 1.1.2.6 | 1.1.2.1 | 1500 | arp, dhcp, icmp 00:00:00:70:00:06 | 1.1.2.7 | 1.1.2.1 | 1500 | arp, dhcp, icmp 00:00:00:70:00:07 | 1.1.2.8 | 1.1.2.1 | 1500 | arp, dhcp, icmp 00:00:00:70:00:08 | 1.1.2.9 | 1.1.2.1 | 1500 | arp, dhcp, icmp 00:00:00:70:00:09 | 1.1.2.10 | 1.1.2.1 | 1500 | arp, dhcp, icmp 00:00:00:70:00:0a | 1.1.2.11 | 1.1.2.1 | 1500 | arp, dhcp, icmp 00:00:00:70:00:0b | 1.1.2.12 | 1.1.2.1 | 1500 | arp, dhcp, icmp 00:00:00:70:00:0c | 1.1.2.13 | 1.1.2.1 | 1500 | arp, dhcp, icmp 00:00:00:70:00:0d | 1.1.2.14 | 1.1.2.1 | 1500 | arp, dhcp, icmp 00:00:00:70:00:0e | 1.1.2.15 | 1.1.2.1 | 1500 | arp, dhcp, icmp 00:00:00:70:00:0f | 1.1.2.16 | 1.1.2.1 | 1500 | arp, dhcp, icmp 00:00:00:70:00:10 | 1.1.2.17 | 1.1.2.1 | 1500 | arp, dhcp, icmp Press Enter to see more clients
|
|
The Router interface is 1.1.2.1. The TRex physical interface is 1.1.2.2. Therefore both these addresses are excluded, and that is why we start from 1.1.2.3. |
If we wait some time, we will see in the DHCPv4 Server counters many more DHCPREQUEST/DHCPACK as part of the lease Renewing process.
trex(service-filtered)>emu_dhcpsrv_show_counters -p 0 --mac 00:00:00:70:00:01 Dhcpsrv Counters name | value --------------+------ activeClients | 250 pktRx | 1250 pktRxDiscover | 250 pktRxRequest | 1000 pktTx | 1250 pktTxOffer | 250 pktTxAck | 1000 6.31 [ms]
DHCPv4 Server with Proxy
Please make yourself familiar with the [Proxy] architecture prior to continuing. In this example we will override the IP address of a TAP interface using the DHCPv4 Server. The profile we use in this example is located here: emu/dhcpsrv_local.py
First let us create the TAP:
$ pwd
trex-emu/scripts
$ sudo ./mktapWe can verify that the TAP is created:
$ ifconfig tap0 Link encap:Ethernet HWaddr 22:55:f6:f0:e8:70 inet addr:11.0.0.1 Bcast:0.0.0.0 Mask:255.255.255.0 UP BROADCAST MULTICAST MTU:1500 Metric:1 RX packets:0 errors:0 dropped:0 overruns:0 frame:0 TX packets:0 errors:0 dropped:0 overruns:0 carrier:0 collisions:0 txqueuelen:500 RX bytes:0 (0.0 B) TX bytes:0 (0.0 B)
Next we run the proxy:
$ pwd
trex-emu/scripts
$ sudo ./proxyThen, we run TRex-Emu:
$ pwd
trex-core/scripts
$ sudo ./trex-emuNow we connect to the Emu using the console and load the profile:
$ ./trex-console --emu-only-server emu>emu_load_profile -f emu/dhcpsrv_local.py -t -h usage: trex_console.py [-h] [--srv_ip SRV_IP] [--srv_dg_ip SRV_DG_IP] Argparser for DHCPv4 Server with Proxy. optional arguments: -h, --help show this help message and exit --srv_ip SRV_IP Server IPv4 (default: 11.0.0.2) --srv_dg_ip SRV_DG_IP Server Default Gateway (default: 11.0.0.1) 13.84 [ms] emu>emu_load_profile -f emu/dhcpsrv_local.py #Converting file to profile [SUCCESS] Converting profile took: 4.00 [ms] Removing old emu profile [SUCCESS] Sending emu profile [SUCCESS] Sending profile took: 19.78 [ms] 25.83 [ms]
| Load the profile |
We can see that the DHCPv4 Server has resolved the default gateway’s MAC using ARP.
emu>emu_show_client_info -p 0 --mac 00:00:00:70:00:01 --json { "mac": "00:00:00:70:00:01", "ipv4_force_dg": false, "ipv6": "::", "dhcp_ipv6": "::", "ipv6_force_dg": false, "ipv6_local": "fe80::200:ff:fe70:1", "dg_ipv6": "::", "ipv4": "11.0.0.2", "plug_names": "arp, dhcpsrv, icmp", "ipv4_dg": "11.0.0.1", "ipv6_dgw": null, "ipv4_mtu": 1500, "ipv6_slaac": "::", "dgw": { "resolve": true, #"rmac": "22:55:f6:f0:e8:70" }, "ipv6_router": null, "ipv4_force_mac": "00:00:00:00:00:00", "ipv6_force_mac": "00:00:00:00:00:00" } 5.10 [ms]
| Default gateway successfully resolved. |
Finally we instruct the TAP to ask for a dynamic address using DHCP.
$ sudo dhclient -4 -v tap0 Internet Systems Consortium DHCP Client 4.2.4 Copyright 2004-2012 Internet Systems Consortium. All rights reserved. For info, please visit https://www.isc.org/software/dhcp/ Listening on LPF/tap0/22:55:f6:f0:e8:70 Sending on LPF/tap0/22:55:f6:f0:e8:70 Sending on Socket/fallback DHCPDISCOVER on tap0 to 255.255.255.255 port 67 interval 3 (xid=0x1b28bf5d) DHCPREQUEST of 11.0.0.3 on tap0 to 255.255.255.255 port 67 (xid=0x5dbf281b) DHCPOFFER of 11.0.0.3 from 11.0.0.2 DHCPACK of 11.0.0.3 from 11.0.0.2 bound to 11.0.0.3 -- renewal in 50 seconds.
We can see the counters of the DHCPv4 Server:
emu>emu_dhcpsrv_show_counters -p 0 --mac 00:00:00:70:00:01 Dhcpsrv Counters name | value ---------------+------ activeClients | 1 pktRx | 5 pktRxBroadcast | 2 pktRxDiscover | 1 pktRxRequest | 4 pktTx | 3 pktTxOffer | 1 pktTxAck | 2 13.63 [ms]
Let us even look at the PCAP file with the traffic:
Note that the TAP sends the first DHCPREQUEST for Renewal after 50 seconds, instead of 60 seconds which is the Renewal Time send in the DHCPACK packet. As such the first two DHCPREQUEST packets sent from the TAP are not answered, while the third DHCPREQUEST which happens after 62 seconds, is.
3.5. Tutorial: IPv6/MLDv2/DHCPV6
- Goal
-
Add clients with static IPv6 and global SLAAC IPv6 address and DHCPv6
IPv6 client side is based on the following RFCs:
-
RFC 4443
-
RFC 4861
-
RFC 4862
-
MLD1/MLDv2 RFC 3810 - support (g,s) filter for MLD2 version
It was written from scratch so it might have some issues.
class Prof1(): def __init__(self): self.mac = Mac('00:00:00:70:00:01') self.def_ns_plugs = {'ipv6' : {'dmac':self.mac.V()}} #self.def_c_plugs = None def create_profile(self, ns_size, clients_size): ns_list = [] # create different namespace each time vport, tci, tpid = 0, [0, 0], [0x00, 0x00] for j in range(vport, ns_size + vport): ns_key = EMUNamespaceKey(vport = j, tci = tci, tpid = tpid) ns = EMUNamespaceObj(ns_key = ns_key, def_c_plugs = self.def_c_plugs) mac = self.mac ipv6 = Ipv6("2001:DB8:1::2") # create a different client each time for i in range(clients_size): client = EMUClientObj(mac = mac[i].V(), ipv6 = ipv6[i].V(), plugs = {'ipv6': {}, 'dhcpv6': {},#
}, ) ns.add_clients(client) ns_list.append(ns) return EMUProfile(ns = ns_list, def_ns_plugs = self.def_ns_plugs) def get_profile(self, tuneables): args = get_args.get_args(tuneables) return self.create_profile(args.ns, args.clients)
def_ns_plugs add ipv6 and 'dhcpv6' : {'dmac':[0,0,0,0x70,0,1]}. This will add the first client as a designator for MLDv2.
| |
Client plugins add ipv6 and dhcpv6
|
ipv6 nd cache interface-limit 1000 ipv6 unicast-routing ipv6 dhcp pool p1 address prefix 2001:DB8:1201::/64 dns-server 2001:DB8:3000:3000::42 domain-name cisco.com ! ipv6 multicast-routing ipv6 multicast rpf use-bgp ! interface TenGigabitEthernet1/0/0 mac-address 0000.0001.0000 mtu 9050 ip address 1.1.5.1 255.255.255.0 load-interval 30 ipv6 address 2001:DB8:1::1/64 ipv6 address 2001:DB8:4:2222::1/64 ipv6 enable ipv6 dhcp server p1 ipv6 mld query-timeout 10 ipv6 mld query-interval 5 !
trex>emu_load_profile -f emu/simple_ipv6.py -t --ns 1 --clients 10 trex>emu_show_client_info -p 0 --mac 00:00:00:70:00:01 --json { "ipv6_force_mac": "00:00:00:00:00:00", "ipv6_dgw": "None", "ipv4_force_dg": false, "plug_names": [ "dhcpv6", "ipv6" ], "mac": "00:00:00:70:00:01", "ipv4_force_mac": "00:00:00:00:00:00", "ipv6_local": "fe80::200:ff:fe70:1", "ipv6_force_dg": false, "ipv6_router": { "mtu": 9050, "prefix": "2001:db8:1::", "prefix_len": 64, "dgmac": "00:00:00:01:00:00", "ipv6": "fe80::200:ff:fe01:0" }, "ipv4": "0.0.0.0", "dg_ipv6": "::", "ipv4_dg": "0.0.0.0", "ipv6": "2001:db8:1::2", "ipv4_mtu": 1500, "dgw": "None", "ipv6_slaac": "2001:db8:1:0:200:ff:fe70:1", "dhcp_ipv6": "2001:DB8:1201::1" } 94.06 [ms] trex>emu_show_all Namespace #1 Information Port | Vlan tags | Tpids | Plugins | Clients -----+-----------+-------+----------+--------- 0 | - | - | - | 10 Clients Information MAC | MTU | IPv6 | DHCP DG-IPv6 | IPv6 Local | ------------------+------+---------------+--------------+---------------------+--- 00:00:00:70:00:01 | 1500 | 2001:db8:1::2 | 2001:DB8:1201::1| fe80::200:ff:fe70:1 | 00:00:00:70:00:02 | 1500 | 2001:db8:1::3 | 2001:DB8:1201::2| fe80::200:ff:fe70:2 | 00:00:00:70:00:03 | 1500 | 2001:db8:1::4 | 2001:DB8:1201::3| fe80::200:ff:fe70:3 | 00:00:00:70:00:04 | 1500 | 2001:db8:1::5 | 2001:DB8:1201::4| fe80::200:ff:fe70:4 | 00:00:00:70:00:05 | 1500 | 2001:db8:1::6 | 2001:DB8:1201::5| fe80::200:ff:fe70:5 | 00:00:00:70:00:06 | 1500 | 2001:db8:1::7 | 2001:DB8:1201::6| fe80::200:ff:fe70:6 | 00:00:00:70:00:07 | 1500 | 2001:db8:1::8 | 2001:DB8:1201::7| fe80::200:ff:fe70:7 | 00:00:00:70:00:08 | 1500 | 2001:db8:1::9 | 2001:DB8:1201::8| fe80::200:ff:fe70:8 | 00:00:00:70:00:09 | 1500 | 2001:db8:1::a | 2001:DB8:1201::9| fe80::200:ff:fe70:9 | 00:00:00:70:00:0a | 1500 | 2001:db8:1::b | 2001:DB8:1201::10| fe80::200:ff:fe70:a 1.31 [sec] trex>emu_dhcpv6_show_counters -p 0 --mac 00:00:00:70:00:01 Dhcpv6 Counters name | value --------------+------ pktTxDiscover | 1 pktRxOffer | 1 pktTxRequest | 1 pktRxAck | 1 pktRxNotify | 1 trex>emu_ipv6_show_cache -p 0 Ipv6 Cache state | mac | refc | resolve | ipv6 ------+-------------------+------+---------+-------------------- 16 | 00:00:00:01:00:00 | 0 | True | fe80::200:ff:fe01:0 359.88 [ms] trex>emu_ipv6_show_mld -p 0 Current mld: ff02::1 ff02::1:ff70:9 ff02::1:ff00:a ff02::1:ff70:5 ff02::1:ff00:6 ff02::1:ff70:7 ff02::1:ff00:8 ff02::1:ff70:1 ff02::1:ff00:2 ff02::1:ff70:8 ff02::1:ff00:9 ff02::1:ff70:2 ff02::1:ff00:3 ff02::1:ff70:3 ff02::1:ff00:4 ff02::1:ff70:6 ff02::1:ff00:7 ff02::1:ff70:4 ff02::1:ff00:5 ff02::1:ff70:a ff02::1:ff00:b ff02::1:ffa7:37e ff02::1:ffb0:a3cc ff02::1:ff38:6001 ff02::1:ff53:5155 ff02::1:ff83:2c7c ff02::1:ff20:5fbe ff02::1:ffd3:8103 ff02::1:ff58:6891 ff02::1:ffd5:2abf ff02::1:ff6b:eb42 225.61 [ms]
trex>emu_ipv6_remove_mld_sg -p 0 --6g ff07::9 --6s 2001:db8:1::cc --6s-count 5
trex>emu_ipv6_add_mld_sg -p 0 --6g ff07::9 --6s 2001:db8:1::cc --6s-count 5
trex>emu_ipv6_show_mld -p 0
Current Mld:
IPv6 | Ref.Count | From RPC | Mode | Sources | S
------------------+-----------+----------+------+---------+--------------
ff02::1 | 1 | False | 1 | 0 |
ff02::1:ff70:1 | 1 | False | 1 | 0 |
ff02::1:ff00:2 | 1 | False | 1 | 0 |
ff02::1:ffc5:47da| 1 | False | 1 | 0 |
>> ff07::9 | 0 | True | 2 | 5 | [2001:db8:1::cf] ..
>#show ipv6 mld groups FF07::9 detail
Interface: TenGigabitEthernet0/0/0
Group: FF07::9
Uptime: 00:00:06
Router mode: INCLUDE
Host mode: INCLUDE
Last reporter: FE80::200:FF:FE70:1
Group source list:
Source Address Uptime Expires Fwd Flags
2001:DB8:1::CC 00:00:06 00:04:13 Yes Remote 4
2001:DB8:1::CD 00:00:06 00:04:13 Yes Remote 4
2001:DB8:1::CE 00:00:06 00:04:13 Yes Remote 4
2001:DB8:1::CF 00:00:06 00:04:13 Yes Remote 4
>show ipv6 dhcp statistics Messages received 152918 Messages sent 142604 Messages discarded 10314 Messages could not be sent 0 Messages Received SOLICIT 141422 REQUEST 761 RELEASE 10735 Messages Sent ADVERTISE 141422 REPLY 1182 Messages discarded due to: Reason Count Invalid options 10314 >show ipv6 neighbors IPv6 Address Age Link-layer Addr State Interface 2001:DB8:1::2 0 0000.0070.0001 STALE Te1/0/0 2001:DB8:1::3 0 0000.0070.0002 STALE Te1/0/0 2001:DB8:1::4 0 0000.0070.0003 STALE Te1/0/0 2001:DB8:1::5 0 0000.0070.0004 STALE Te1/0/0 2001:DB8:1::6 0 0000.0070.0005 STALE Te1/0/0 2001:DB8:1::7 0 0000.0070.0006 STALE Te1/0/0 2001:DB8:1::8 0 0000.0070.0007 STALE Te1/0/0 2001:DB8:1::9 0 0000.0070.0008 STALE Te1/0/0 2001:DB8:1::A 0 0000.0070.0009 STALE Te1/0/0 2001:DB8:1::B 0 0000.0070.000a STALE Te1/0/0 2001:DB8:1:0:200:FF:FE70:1 0 0000.0070.0001 STALE Te1/0/0 2001:DB8:1:0:200:FF:FE70:2 0 0000.0070.0002 STALE Te1/0/0 2001:DB8:1:0:200:FF:FE70:3 0 0000.0070.0003 STALE Te1/0/0 2001:DB8:1:0:200:FF:FE70:4 0 0000.0070.0004 STALE Te1/0/0 2001:DB8:1:0:200:FF:FE70:5 0 0000.0070.0005 STALE Te1/0/0 2001:DB8:1:0:200:FF:FE70:6 0 0000.0070.0006 STALE Te1/0/0 2001:DB8:1:0:200:FF:FE70:7 0 0000.0070.0007 STALE Te1/0/0 2001:DB8:1:0:200:FF:FE70:8 0 0000.0070.0008 STALE Te1/0/0 2001:DB8:1:0:200:FF:FE70:9 0 0000.0070.0009 STALE Te1/0/0 2001:DB8:1:0:200:FF:FE70:A 0 0000.0070.000a STALE Te1/0/0 2001:DB8:1201:0:1058:160:2D6B:EB42 0 0000.0070.000a STALE Te1/0/0 2001:DB8:1201:0:4097:A4E8:72A7:37E 0 0000.0070.0009 STALE Te1/0/0 2001:DB8:1201:0:6CCE:E021:7753:5155 0 0000.0070.0001 STALE Te1/0/0 2001:DB8:1201:0:6DF5:1CCC:D7D5:2ABF 0 0000.0070.0004 STALE Te1/0/0 2001:DB8:1201:0:8559:F959:E258:6891 0 0000.0070.0006 STALE Te1/0/0 2001:DB8:1201:0:89E5:B4B3:F238:6001 0 0000.0070.0007 STALE Te1/0/0 2001:DB8:1201:0:9DA9:7803:E3B0:A3CC 0 0000.0070.0005 STALE Te1/0/0 2001:DB8:1201:0:C4E7:2D31:8683:2C7C 0 0000.0070.0008 STALE Te1/0/0 2001:DB8:1201:0:DDEE:C998:F120:5FBE 0 0000.0070.0002 STALE Te1/0/0 2001:DB8:1201:0:F525:CCA0:79D3:8103 0 0000.0070.0003 STALE Te1/0/0 FE80::200:FF:FE70:1 0 0000.0070.0001 STALE Te1/0/0 FE80::200:FF:FE70:2 0 0000.0070.0002 STALE Te1/0/0 FE80::200:FF:FE70:3 0 0000.0070.0003 STALE Te1/0/0 FE80::200:FF:FE70:4 0 0000.0070.0004 STALE Te1/0/0 FE80::200:FF:FE70:5 0 0000.0070.0005 REACH Te1/0/0 FE80::200:FF:FE70:6 0 0000.0070.0006 STALE Te1/0/0 FE80::200:FF:FE70:7 0 0000.0070.0007 STALE Te1/0/0 FE80::200:FF:FE70:8 0 0000.0070.0008 STALE Te1/0/0 FE80::200:FF:FE70:9 0 0000.0070.0009 REACH Te1/0/0 FE80::200:FF:FE70:A 0 0000.0070.000a STALE Te1/0/0 >show ipv6 mld groups MLD Connected Group Membership Group Address Interface FF05::1:3 Te1/0/0 >show ipv6 mld traffic MLD Traffic Counters Elapsed time since counters cleared: 7w0d Received Sent Valid MLD Packets 19156 129235 Queries 0 76308 Reports 19156 52927 Leaves 0 0 Mtrace packets 0 0 Errors: Malformed Packets 0 Martian source 0 Non link-local source 0 Hop limit is not equal to 1 0 >ping ipv6 2001:DB8:1::2 Type escape sequence to abort. Sending 5, 100-byte ICMP Echos to 2001:DB8:1::2, timeout is 2 seconds: !!!!! Success rate is 100 percent (5/5), round-trip min/avg/max = 101/108/117 ms
-
Every client advertises all its global IPv6 addresses using NS packets and its own local-IPv6.
-
MLDv2 is used (MLDv1 is supported too but less efficient) to publish the solicited multicast address for each IPv6 global address.
-
DHCPv6 does not offer a default gateway, SLAAC can be used or an explicit address.
3.6. Tutorial: Dot1x
- Goal
-
To authenticate up to 2000 clients on one ports of C9300 switch (up to 50K per switch)
EMU can supports EAP-MD5 and EAP-MSCHAPv2 (PEAP, TTLS and EAP-TLS is not supported yet). Multi-AUTH and Single host is supported (multicast and unicast)
client switch1 {
ipv4addr = *
secret = switch1
}switch1 will be the salt of the Switch client
Let’s add a few users to the Radius:
test1 Cleartext-Password := "test1" test2 Cleartext-Password := "test2" test3 Cleartext-Password := "test3" test4 Cleartext-Password := "test4" test5 Cleartext-Password := "test5" test6 Cleartext-Password := "test6" test7 Cleartext-Password := "test7" test8 Cleartext-Password := "test8" test9 Cleartext-Password := "test9"
radtest -t eap-md5 test1 test1 1.1.1.2 0 switch1
dot1x system-auth-control dot1x eapol version 2 dot1x logging verbose radius server rad1 address ipv4 1.1.1.2 auth-port 1812 acct-port 1813 key switch1 aaa group server radius radg1 server name rad1 ! aaa authentication dot1x default group rad1g interface GigabitEthernet2/0/21 switchport access vlan 2000 switchport mode access authentication timer reauthenticate 1 access-session host-mode multi-auth access-session control-direction in access-session port-control auto dot1x pae authenticator dot1x timeout quiet-period 1 dot1x timeout server-timeout 1 dot1x timeout tx-period 1 dot1x timeout start-period 1 dot1x timeout held-period 1 dot1x timeout auth-period 1 spanning-tree portfast service-policy type control subscriber DOT1X-1 policy-map type control subscriber DOT1X-1 event session-started match-all 10 class always do-all 10 authenticate using dot1x priority 10
class Prof1(): def __init__(self): self.def_ns_plugs = None self.def_c_plugs = None def create_profile(self, ns_size, clients_size): ns_list = [] # create different namespace each time vport, tci, tpid = 0, [0, 0], [0x00, 0x00] for j in range(vport, ns_size + vport): ns_key = EMUNamespaceKey(vport = j, tci = tci, tpid = tpid) ns = EMUNamespaceObj(ns_key = ns_key, def_c_plugs = self.def_c_plugs) mac = Mac('00:00:00:70:00:01') ipv4 = Ipv4('1.1.5.2') dg = Ipv4('1.1.5.1') u = "test{}".format(i+1) # create a different client each time for i in range(clients_size): client = EMUClientObj(mac = mac[i].V(), ipv4 = ipv4[i].V(), ipv4_dg = dg.V(), plugs = {'arp': {}, 'icmp': {}, 'dot1x': {'user':u, 'password':u, 'flags':1}, }, ) ns.add_clients(client) ns_list.append(ns) return EMUProfile(ns = ns_list, def_ns_plugs = self.def_ns_plugs)
-
To Force MSCHAPv2 add flags:1, this will disable EAP-MD5 (dot1x: {user:u, password:u, flags:1},)
9300-stack-197.72> show dot1x statistics
Dot1x Global Statistics for
--------------------------------------------
RxStart = 8 RxLogoff = 0 RxResp = 10 RxRespID = 13
RxReq = 0 RxInvalid = 0 RxLenErr = 0
RxTotal = 33
TxStart = 0 TxLogoff = 0 TxResp = 0
TxReq = 20 ReTxReq = 0 ReTxReqFail = 3
TxReqID = 13 ReTxReqID = 0 ReTxReqIDFail = 0
TxTotal = 33
9300-stack-197.72> show authentication sessions interface GigabitEthernet 2/0/21
Interface MAC Address Method Domain Status Fg
-------------------------------------------------------------------
Gi2/0/21 0000.0070.0001 dot1x DATA Auth
Gi2/0/21 0000.0070.0002 dot1x DATA Auth
Key to Session Events Blocked Status Flags:
A - Applying Policy (multi-line status for details)
D - Awaiting Deletion
F - Final Removal in progress
I - Awaiting IIF ID allocation
P - Pushed Session
R - Removing User Profile (multi-line status for details)
U - Applying User Profile (multi-line status for details)
X - Unknown Blocker
Runnable methods list:
Handle Priority Name
9 5 dot1x
7 5 dot1xSup
13 10 webauth
10 15 mab3.7. Tutorial: DNS
The Domain Name System DNS is a hierarchical and decentralized naming system for computers, services, or other resources connected to the Internet or a private network. It associates various information with domain names assigned to each of the participating entities. Most prominently, it translates more readily memorized domain names to the numerical IP addresses needed for locating and identifying computer services and devices with the underlying network protocols. By providing a worldwide, distributed directory service, the Domain Name System has been an essential component of the functionality of the Internet since 1985.
EMU implements a simple version of DNS based RFCs 1034, 1035. EMU clients can emulate both DNS Resolvers and
DNS Name Servers, as such providing both Client and Server side.
Dns Resolvers:
-
Query
-
Hold Response Cache
-
Hold Counters
Dns Name Servers:
-
Own a domain database
-
Respond to queries
-
Can add/remove domains dynamically
-
Hold Counters
Let’s dive right into defining an EMU Client with DNS.
3.7.1. Dns Client Init Json
|
|
For an updated version of the fields refer to the SDK. |
To define a DNS Resolver:
initJson = { "name_server": False,"dns_server_ip": dns_ip
}
In order to define a resolver, simple set name_server to False. This is the default choice.
| |
| Each resolver needs an Ip for the Dns Server. This Ip can be IPv4 or IPv6. Currently only one IP is supported. The field is mandatory for Dns resolvers. |
To define a DNS Name Server:
initJson = { "name_server": True,"database": {
"trex-tgn.cisco.com": [
{ "type": "A", "class": "IN", "answer": "173.36.109.208" } ], "cisco.com": [ { "type": "A", "class": "IN", "answer": "72.163.4.185" }, { "type": "A",
"class": "IN", "answer": "72.163.4.161" }, { "type": "AAAA",
"class": "IN", "answer": "2001:420:1101:1::185" }, { "type": "TXT",
"class": "IN", "answer": "desc=Best place to work!, location=Israel" } ], "8.8.8.8.in-addr.arpa": [ { "type": "PTR",
"class": "IN", "answer": "google.com" } ] } }
In order to define a DNS Name Server we need to set this field to True.
| |
| For DNS Name Server we must provide a database. The database is a dictionary where each key represents a domain. This field is mandatory for Dns Name Servers and ignored for Dns Resolvers. | |
| Each domain holds a list of DNS Entries, where each entry consists of a Dns Type, Dns Class and Answer. | |
| Note that multiple entries of the same type/class can be held. The server will answer with all the relevant entries. | |
| An example of an AAAA type answer. | |
| An example of defining a TXT answer. Note the format, each two fields should be separated by a comma. | |
| An example of a PTR type entry. |
|
|
Currently we support only the following DNS Types: A, AAAA, PTR, TXT. |
3.7.2. Console Api
Let’s load the provided profile simple_dns and see what operations we can do from the Console.
trex(service-filtered)>emu_load_profile -f emu/simple_dns.py -t -h usage: trex_console.py [-h] [--ns NS] [--clients CLIENTS] [--ipv6] Argparser for simple Emu Dns profile. optional arguments: -h, --help show this help message and exit --ns NS Number of namespaces to create --clients CLIENTS Number of clients to create in each namespace #--ipv6 Use Ipv6 instead of Ipv4 #
| In this profile, the first client is the Name Server, all the rest are resolvers. | |
| You can decide to use Ipv6 instead of Ipv4 but make sure your topology supports it. |
For Name Server, we can see it’s domains:
trex(service-filtered)>emu_dns_show_domains -p 0 --mac 00:00:00:70:00:03 Domains Number | Domain -------+--------------------- 1 | trex-tgn.cisco.com 2 | cisco.com 3 | 8.8.8.8.in-addr.arpa
We can also see the domain entries:
trex(service-filtered)>emu_dns_show_domain_entries -p 0 --mac 00:00:00:70:00:03 -d cisco.com Cisco.Com Entries Answer | Type | Class ---------------------+------+------ 72.163.4.185 | A | IN 72.163.4.161 | A | IN 2001:420:1101:1::185 | AAAA | IN
|
|
TXT entries are not displayed in the console since they are long. |
For Resolvers, we can query and explore the cache:
trex(service-filtered)>emu_dns_query -p 0 --mac 00:00:00:70:00:04 -n trex-tgn.cisco.com #[SUCCESS] trex(service-filtered)>emu_dns_show_cache -p 0 --mac 00:00:00:70:00:04 Dns Cache Domain | Answer | Type | Class | Time To Live | Time Left -------------------+----------------+------+-------+--------------+---------- trex-tgn.cisco.com | 173.36.109.208 | A | IN | 240 | 215
| It will query the the Dns Name Server whose IP we defined in the Init Json for this Dns Resolver. |
We can see in the following two pictures the query and the response:
If we query a domain which is not found in the Name Server Database, we will get an appropriate response:
trex(service-filtered)>emu_dns_query -p 0 --mac 00:00:00:70:00:04 -n github.com #[SUCCESS]
| Note that the domain is not found in the database. |
In queries we can specify the class and the type of Dns Query:
trex(service-filtered)>emu_dns_query -p 0 --mac 00:00:00:70:00:04 -n cisco.com -t AAAA [SUCCESS] trex(service-filtered)>emu_dns_show_cache -p 0 --mac 00:00:00:70:00:04 Dns Cache Domain | Answer | Type | Class | Time To Live | Time Left -------------------+----------------------+------+-------+--------------+---------- trex-tgn.cisco.com | 173.36.109.208 | A | IN | 240 | 160 cisco.com | 2001:420:1101:1::185 | AAAA | IN | 240 | 239
We can flush the cache:
trex(service-filtered)>emu_dns_flush_cache -p 0 --mac 00:00:00:70:00:04 [SUCCESS] trex(service-filtered)>emu_dns_show_cache -p 0 --mac 00:00:00:70:00:04 No entries in Dns cache.
Finally we can see counters for both Dns Name Server and Dns Resolver.
trex(service-filtered)>emu_dns_show_counters -p 0 --mac 00:00:00:70:00:04 --verbose Dns Counters name | value | unit | zero | help -----------------+-------+-------+------+------------------------------- txBytes | 63 | bytes | True | Number of bytes transmitted rxBytes | 134 | bytes | True | Number of bytes received pktTxDnsQuery | 2 | pkts | True | Num of Dns queries transmitted pktRxDnsResponse | 2 | pkts | True | Num of Dns responses received trex(service-filtered)>emu_dns_show_counters -p 0 --mac 00:00:00:70:00:03 --verbose Dns Counters name | value | unit | zero | help -----------------+-------+-------+------+---------------------------------------------------------- txBytes | 134 | bytes | True | Number of bytes transmitted rxBytes | 63 | bytes | True | Number of bytes received rxQuestions | 2 | ops | True | Number of questions received dnsFlowAccept | 2 | ops | True | Number of Dns flows accepted. Each request is a new flow. pktRxDnsQuery | 2 | pkts | True | Num of Dns queries received pktTxDnsResponse | 2 | pkts | True | Num of Dns responses transmitted
3.7.3. Dns Namespace Init Json
DNS works both at client and namespace level. We already saw how we can define resolvers or name servers as DNS clients. However in order to order to query we must do this explicitly using the console or plugin APIs.
At namespace level we can instruct the clients belonging to that namespace to automatically query. This is called auto_play.
Let’s suppose we defined the following name server:
name_server = { "name_server": True, "database": { "domain1.com": [ { "type": "A", "class": "IN", "answer": "1.1.1.1" }, { "type": "A", "class": "IN", "answer": "1.1.1.2" } ], "domain2.com": [ { "type": "A", "class": "IN", "answer": "2.2.2.2" }, { "type": "AAAA", "class": "IN", "answer": "2001:420:1101:1::2" }, ], "domain3.com": [ { "type": "A", "class": "CH", "answer": "3.3.3.3" } ], "domain4.com": [ { "type": "A", "class": "IN", "answer": "4.4.4.4" }, { "type": "TXT", "class": "IN", "answer": "desc=domain4, gen=trex" } ] } } # add simple entries for domains [5-255] for i in range (5, 256): name_server["database"]["domain{}.com".format(i)] = [ { "type": "A", "class": "IN", "answer": "{}.{}.{}.{}".format(i, i, i, i) } ]
We are defining 255 domains, from domain1.com to domain255.com. Most of the domains contain a simple A type Dns entry, however the first entries are different (type AAAA, TXT, class CH) in order to demonstrate that they are supported.
Now we can define a namespace Init Json just as the one below:
{ "auto_play": True,"auto_play_params": {
"rate": 0.5,
"query_amount": query_amount,
"min_client": "00:00:00:70:00:04",
"max_client": "00:00:00:70:00:{:02x}".format(max_client), "client_step": 1, "hostname_template": "domain%v.com",
"min_hostname": 1, "max_hostname": clients_size -1, "hostname_step": 1, "type": "A",
"class": "IN",
"program": {
"00:00:00:70:00:05": { "hostnames": ["domain2.com"], "type": "AAAA", "class": "IN", }, "00:00:00:70:00:06": { "hostnames": ["domain3.com"], "type": "A", "class": "Any", }, "00:00:00:70:00:07": { "hostnames": ["domain4.com"], "type": "TXT", } } } }
| Should the namespace automatically play traffic? | |
Parameters that define how to play the traffic. The auto_play_params are parsed only if auto_play is True.
| |
Rate in pps between two consecutive query attempts. Let’s assume the rate is 0.5. The first client will send a query at 0.5 seconds. The second client will send a query at 2.5 second, and so on. By attempt, we mean the following:
If the namespace doesn’t find a client whose MAC address we generated, it will do nothing, and continue to the next client in another 0.5 seconds.
| |
| The amount of queries to send. Defaults to 0. In the case of 0, the program will send an infinite amount of queries. | |
Min client and max client specify a range of MAC addresses. We generate MAC addresses in this range using the client_step to increment. Each generated MAC address represents a client. If the namespace has such client, it will send a query using it. If it doesn’t, nothing happens. The reason we prefer MAC addresses to IP addresses is because we support both IPv4 and IPv6. The reason why we use MAC addresses as strings instead of byte arrays is because they can be keys in JSON.
The generation reminds engines. For example, the MAC addresses that will be generated from the shown Json are [00:00:00:70:00:04, 00:00:00:70:00:05, 00:00:00:70:00:06, …, 00:00:00:70:00:04, 00:00:00:70:00:05 …]
| |
A template string to which we apply numbers. The numbers are generated in the domain [min_hostname, max_hostname] using hostname_step. Note that you can also specify where to begin using init_hostname. For example, in the provided Json, we will generate the following hostnames [domain1.com, domain2.com, …, domain1.com, domain2.com …]. The first client will use the first hostname in list as query parameter, the second client the second hostname and so on. If we skip a client because the namespace doesn’t find a client with such MAC address, we also skip the hostname.
| |
| Type of DNS query. Default is A. | |
| Class of DNS query. Default is IN. | |
| Program is a dictionary that allows you to specify special queries for clients. In the shown Json, the client with the MAC address 00:00:00:70:00:05 will send a AAAA type query. The client with the MAC address 00:00:00:70:00:06 will send a query with class Any since if you pay attention in the database, the entry for domain3.com is of class CH. This way we provide full control over queries. However note that if your simulating thousand of clients, you program will be massive and can’t be passed as a Json to the Emu. Hence try to keep the program small. |
|
|
For an updated version of the fields refer to the SDK. |
For a profile containing the example look here: emu/dns_auto_play.py
For your knowledge the mapping between MAC → IP is as follows: 00:00:00:70:00:x → 1.1.1.x
The first client (1.1.1.3) is the name server. The other clients are resolvers and they query domains incrementally. For example client 1.1.1.4 queries domain1.com, client 1.1.1.5 queries domain2.com and so on.
We can see the recorded PCAP from this profile:
A few things we can see from the capture:
-
The first client indeed queries without a specific program.
-
There is a 2 second gap between the queries.
-
The second client queries an
AAAAtype as can be seen in the first picture. -
The third client queries using the
Anyclass and receives aCHclass response as seen in the second picture. -
The fourth client queries a
TXTtype.
3.7.4. Dns Plugin Api
The Console Api is a bit more limited than the Plugin Api. Using the Plugin Api we can make changes in the Name Server dynamically by adding or removing domains and/or domain entries. One such example can be found in the following script: emu_dns.py.
The first part includes setting up the EMU Client and loading the profile.
c = EMUClient(server='localhost', sync_port=4510, verbose_level= "error", logger=None, sync_timeout=None) ns_key = EMUNamespaceKey(vport = 0) c_key = EMUClientKey(ns_key, Mac("00:00:00:70:00:03").V()) # Dns Server # connect and load profile c.connect() c.load_profile(profile = SIMPLE_DNS_PROFILE, tunables = ['--clients', '2'])
We can collect all the domains that a Name Server holds in its database:
# Get domains print("Getting registered domains from Dns Name Server:\n") domains = c.dns.get_domains(c_key)
We can collect the entries for a specific domain:
# See Entries that the profile had defined for cisco.com print("Getting Domain Entries for domain cisco.com:\n") res = c.dns.get_domain_entries(c_key, "cisco.com")
We can remove entries from a domain:
# Remove one entry that exists and attempt to remove one that doesn't exist! print("Will attempt removing the following entries: (only one exists)\n") entriesToRemove = [ {'answer': '72.163.4.161', 'class': 'IN', 'type': 'A'}, # existing {'answer': '72.163.4.165', 'class': 'IN', 'type': 'A'} # non existent ] c.dns.remove_domain_entries(c_key, "cisco.com", entriesToRemove)
|
|
Only existing entries will be removed, non existing entries will be ignored. |
We can add entries (both to existing domains or non existing domains).
# Add one entry that exists and attempt adding twice a new entry. print("Will attempt adding the following entries to domain cisco.com:\n") entriesToAdd = [ {'answer': '72.163.4.185', 'class': 'IN', 'type': 'A'}, # existing {'answer': 'desc=new, exp=add_twice', 'class': 'IN', 'type': 'TXT'}, # non existent {'answer': 'desc=new, exp=add_twice', 'class': 'IN', 'type': 'TXT'} # same as previous ] c.dns.add_domain_entries(c_key, "cisco.com", entriesToAdd)
|
|
Existing entries are ignored. Adding the same entry twice will result only in the first entry being added. |
3.8. Tutorial: mDNS
Before proceeding, make sure you are familiar with the network topology required for mDNS.
Multicast DNS (mDNS) is a protocol aimed at helping with name resolution in smaller networks. In doing so, it takes a different approach than the well-known DNS. Instead of querying a name server, all participants in the network are directly addressed. The appropriate client sends a multicast into the network while asking which network participant matches up with the host name.
|
|
Multicast DNS was developed in the early 2010s and is described in RFC 6762. |
mDNS is one of the only protocols in EMU currently running both at client level and namespace level.
-
Each client owns different hostnames and can query, hence it makes sense to have mDNS at client level.
-
Since the protocol uses multicast, each response can be learned by all the clients, hence we can hold a cache in namespace level instead of per each client. This way we improve performance.
3.8.1. Client level
Init JSON and mDNS definition
To define a client which runs mDNS in Emu, we need to activate it in the client plugins and provide an initial JSON. The JSON supports the following keys:
-
hosts- A list of host names this client owns. -
domain_name- The domain name this client answers when queried with a PTR query. -
txt- A list of name, value entries this client answers when queried with a TXT query. -
ttl- The time to live in seconds for each response the client sends. Defaults to 240.
For a more updated version refer to the SDK.
initJson = { "hosts": ['UCS', 'trex-04', "10.56.1.1.cisco.il.lab"],"txt": [ { "field": "HW", "value": "Cisco UCS 220M5" }, { "field": "OS", "value": "Ubuntu 20.04", } ], "domain_name": "cisco.il.lab", "ttl": 180, }
| Note that you can add an IP address as a host for PTR queries. |
We need to apply the mDNS plugin both at namespace and client level like this:
self.def_ns_plugs = {'icmp': {}, 'arp' : {'enable': True}, 'mdns': {},'ipv6' : {'dmac':Mac('00:00:00:70:00:01').V()}} }
| Apply mDNS as a namespace plugin. |
client = EMUClientObj(mac = Mac('00:00:00:70:00:05').V(), ipv4 = Ipv4('1.1.1.5').V(), ipv4_dg = Ipv4('1.1.1.1').V(), ipv6 = Ipv6("2001:DB8:1::5").V(), plugs = {'mdns': initJson,'ipv6': {} })
| Apply mDNS as a client plugin with the init Json we defined before. |
Let us suppose we have created a profile with mDNS, and it looks this:
trex(service-filtered)>emu_show_all Namespace 1 Information Port | Vlan tags | Tpids | Plugins | Clients -----+-----------+-------+-----------------------+--------- 0 | - | - | arp, icmp, ipv6, mdns | 2 Clients Information MAC | IPv4 | DG-IPv4 | MTU | Plugins ------------------+---------+----------+------+---------------------- 00:00:00:70:00:03 | 1.1.1.3 | 1.1.1.16 | 1500 | arp, icmp, ipv6, mdns 00:00:00:70:00:04 | 1.1.1.4 | 1.1.1.16 | 1500 | arp, icmp, ipv6, mdns Press Enter to see more namespaces Namespace 2 Information Port | Vlan tags | Tpids | Plugins | Clients -----+-----------+-------+-----------------------+--------- 1 | - | - | arp, icmp, ipv6, mdns | 2 Clients Information MAC | IPv4 | DG-IPv4 | MTU | Plugins ------------------+---------+---------+------+---------------------- 00:00:00:70:00:05 | 1.1.1.5 | 1.1.1.1 | 1500 | arp, icmp, ipv6, mdns 00:00:00:70:00:06 | 1.1.1.6 | 1.1.1.1 | 1500 | arp, icmp, ipv6, mdns 1.80 [sec]
Add, Remove and Show Hosts
We can see the hostnames of each client:
trex(service-filtered)>emu_mdns_show_hosts -p 1 --mac 00:00:00:70:00:05 Hostnames Number | Hostname -------+----------------------- 1 | UCS 2 | trex-04 3 | 10.56.1.1.cisco.il.lab
We can add hostnames to each client:
trex(service-filtered)>emu_mdns_add_hosts -p 1 --mac 00:00:00:70:00:05 --hosts vxnet3 docs.local UCS Hosts: ['UCS'] were not added because they already exist. #[SUCCESS] trex(service-filtered)>emu_mdns_show_hosts -p 1 --mac 00:00:00:70:00:05 Hostnames Number | Hostname -------+----------------------- 1 | UCS 2 | trex-04 3 | 10.56.1.1.cisco.il.lab 4 | vxnet3 5 | docs.local
| UCS already existed but the other hostnames were added successfully. |
We can remove hostnames from each client:
trex(service-filtered)>emu_mdns_remove_hosts -p 1 --mac 00:00:00:70:00:05 --hosts docs.local invalid Hosts: ['invalid'] did not exist. #[SUCCESS] trex(service-filtered)>emu_mdns_show_hosts -p 1 --mac 00:00:00:70:00:05 Hostnames Number | Hostname -------+----------------------- 1 | trex-04 2 | 10.56.1.1.cisco.il.lab 3 | vxnet3 4 | UCS
| The existing hostnames are removed correctly. |
Query and Cache
We can query with different possibilities:
trex(service-filtered)>emu_mdns_query -p 0 --mac 00:00:00:70:00:03 -n trex-04 #[SUCCESS] trex(service-filtered)>emu_mdns_query -p 0 --mac 00:00:00:70:00:03 -n trex-04 -t AAAA #
[SUCCESS] trex(service-filtered)> trex(service-filtered)>emu_mdns_query -p 0 --mac 00:00:00:70:00:03 -n vxnet3 -6 -t TXT #
[SUCCESS] trex(service-filtered)>emu_mdns_query -p 0 --mac 00:00:00:70:00:03 -n 10.56.1.1.cisco.il.lab -t PTR #
[SUCCESS] trex(service-filtered)>emu_mdns_query -p 0 --mac 00:00:00:70:00:03 -n UCS -c Any #
[SUCCESS]
| The default DNS type is A and the default DNS class is IN. | |
| We can send AAAA queries. | |
| -6 represents that the packet should be sent using IPv6. TXT queries are supported as well. | |
| We can also send PTR queries. | |
| We can also set the class to Any. |
|
|
We support only A, AAAA, PTR and TXT types at the moment. Also, QU is
|
Let us see the resolved entries in the DNS cache table like this:
trex(service-filtered)>emu_mdns_show_cache -p 0 Resolved Hostnames Hostname | Answer | Type | Class | Time To Live | Time Left -----------------------+----------------+------+-------+--------------+---------- UCS | 1.1.1.5 | A | Any | 180 | 179 trex-04 | 1.1.1.5 | A | IN | 180 | 61 trex-04 | 2001:db8:1::5 | AAAA | IN | 180 | 75 10.56.1.1.cisco.il.lab | cisco.il.lab | PTR | IN | 180 | 122
|
|
Only A, AAAA, and PTR responses are added to the table. The time to live can be set in the init Json of the responding client. |
We can see the response to the PTR query:
And the response to the TXT query:
As mentioned before, since the protocol uses multicast the cache table is shared between all the clients in the same namespace and is held at namespace level.
The cache can be flushed like this:
trex(service-filtered)>emu_mdns_flush_cache -p 0 [SUCCESS] trex(service-filtered)>emu_mdns_show_cache -p 0 No entries in mDNS cache.
3.8.2. Counters
In mDNS there are counters both at client and namespace level which you can access:
trex(service-filtered)>emu_mdns_show_c_counters -p 1 --mac 00:00:00:70:00:05 Mdns Counters name | value ------------------+------ pktRxMDnsQuery | 5 pktTxMDnsResponse | 5 11.65 [ms] trex(service-filtered)>emu_mdns_show_ns_counters -p 0 -v Mdns Counters name | value | unit | zero | help ----------+-------+-------+------+------------------------------------------- rxPkts | 5 | pkts | True | Num of mDNS pkts received rxAnswers | 5 | reply | True | Numb of mDNS answers received in namespace
3.8.3. Namespace level
We already saw that there are mDNS counters per namespace. We also saw that the cache is held per namespace. Yet, this is not all there is to mDNS in namespace level. Using the Init Json for namespace, we can instruct the namespace to automatically generate mDNS traffic. Let’s look at a simple example and try to understand the idea behind it.
|
|
For all the details and default values, please check the SDK of mDNS. |
{ "auto_play": True,"auto_play_params": {
"rate": 2.0,
"query_amount": 100,
"min_client": "00:00:00:70:00:02",
"max_client": "00:00:00:70:00:06", "client_step": 2, "hostname_template": "trex-client-%v._tcp.local",
"min_hostname": 1, "max_hostname": 5, "hostname_step": 2, "type": "A",
"class": "IN",
"ipv6": False,
"program": {
"00:00:00:70:00:02": { "hostnames": ["emu-client-1._tcp.local", "trex-client-1._tcp.local"], "type": "TXT", "class": "Any", "ipv6": True } } } }
| Should the namespace automatically play traffic? | |
Parameters that define how to play the traffic. The auto_play_params are parsed only if auto_play is True.
| |
Rate in pps between two consecutive query attempts. Let’s assume the rate is 2.0. The first client will send a query at 0.5 seconds. The second client will send a query at 1 second, and so on. By attempt, we mean the following:
If the namespace doesn’t find a client whose MAC address we generated, it will do nothing, and continue to the next client in another 0.5 seconds.
| |
| The amount of queries to send. In this case, after 100 queries, the program will stop sending queries. Defaults to 0. In the case of 0, the program will send an infinite amount of queries. | |
Min client and max client specify a range of MAC addresses. We generate MAC addresses in this range using the client_step to increment. Each generated MAC address represents a client. If the namespace has such client, it will send a query using it. If it doesn’t, nothing happens. The reason we prefer MAC addresses to IP addresses is because we support both IPv4 and IPv6. The reason why we use MAC addresses as strings instead of byte arrays is because they can be keys in JSON.
The generation reminds engines. For example, the MAC addresses that will be generated from the shown Json are [00:00:00:70:00:02, 00:00:00:70:00:04, 00:00:00:70:00:06, 00:00:00:70:00:03, 00:00:00:70:00:05, 00:00:00:70:00:02…]
| |
A template string to which we apply numbers. The numbers are generated in the domain [min_hostname, max_hostname] using hostname_step. Note that you can also specify where in the domain to begin using init_hostname. For example, in the provided Json, we will generate the following hostnames [trex-client-1._tcp.local, trex-client-3._tcp.local, trex-client-5._tcp.local, trex-client-2._tcp.local, trex-client-4._tcp.local, trex-client-1._tcp.local…]. The first client will use the first hostname in list as query parameter, the second client the second hostname and so on. If we skip a client because the namespace doesn’t find a client with such MAC address, we also skip the hostname.
| |
| Type of mDNS query. Default is A. | |
| Class of mDNS query. Default is IN. | |
| Should the queries be sent using IPv6. Will work only if client has an IPv6 address. | |
| Program is a dictionary that allows you to specify special queries for clients. In the shown Json, the client with the MAC address 00:00:00:70:00:02 will send a TXT type query, of class Any using IPv6 to both hostnames ["emu-client-1", "trex-client-1"] overriding the default query pattern. This way we provide full control over queries. However note that if your simulating thousand of clients, you program will be massive and can’t be passed as a Json to the Emu. Hence try to keep the program small. |
The following PCAP shows the generated a small portion of the generated traffic:
|
|
Each packet is duplicated because this is captured in a loopback. |
For your knowledge the mapping between MAC → IP is as follows: 00:00:00:70:00:x → 1.1.1.x
A few things we can see from the capture:
-
The first client indeed sends IPv6 and a TXT query.
-
The time difference between two queries is 0.5 seconds because the rate is 2.0. However note that after 1.1.1.7 there is a 2 second gap. This is because the namespace doesn’t have clients 00:00:00:70:00:03 and 00:00:00:70:00:05.
-
Note how the hostnames are generated. When we skipped clients, we also skipped hostnames.
3.9. Tutorial: Netflow
NetFlow is a feature that was introduced on Cisco routers around 1996 that provides the ability to collect IP network traffic as it enters or exits an interface. By analyzing the data provided by NetFlow, a network administrator can determine things such as the source and destination of traffic, class of service, and the causes of congestion. A typical flow monitoring setup (using NetFlow) consists of three main components:
-
Flow exporter: aggregates packets into flows and exports flow records towards one or more flow collectors.
-
Flow collector: responsible for reception, storage and pre-processing of flow data received from a flow exporter.
-
Analysis application: analyzes received flow data in the context of intrusion detection or traffic profiling, for example.
TRex EMU emulates the aforementioned flow exporter for Netflow v9, RFC 3954 and Netflow v10 (IPFix), RFC 7011.
We designed our Netflow plugin to have the most generic and modular implementation that we can provide. As such we first introduce a new EMU object called engine.
Prior to proceeding into the Netflow plugin, knowledge of engines is required. Please refer to the engines section:
3.9.1. Netflow EMU Client Plugin
In order to configure an EMU client to generate and export IPFIX records, the user has to provide a corresponding plugin initialization JSON when the EMU client is created. This JSON is used among other things to define:
-
The content of generated Netflow/IPFIX template and data records.
-
The rate at which records of each type are generated.
-
Where to export the generated IPFIX records and how.
Some of the configuration parameters can also be updated after the EMU client was created via API or console commands. Note that all parameters in this JSON are optional unless stated otherwise.
Let us take a look at an example init JSON:
{ "netflow_version": 10, "dst": "http://48.0.0.0:4739", "domain_id": 7777, "max_template_records": 0, "max_data_records": 0, "max_time": "300s", "auto_start": true, "exporter_params": { "max_size": 1048576, "max_interval": "60s", "max_files": 100, "max_posts": 0, "compress": true, }, "generators": [ { "name": "mix1", "auto_start": true, "rate_pps": 1, "data_records_num": 2, "template_id": 261, "is_options_template": true, "scope_count": 1, "fields": [ { "name": "clientIPv4Address", "type": 45004, "length": 4, "enterprise_number": 9, "data": [16, 0, 0, 1] }, { "name": "protocolIdentifier", "type": 4, "length": 1, "data": [17] }, { "name": "nbar2HttpHost", "type": 45003, "length": 60, "enterprise_number": 9, "data":[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] } ], "engines": [ { "engine_name": "clientIPv4Address", "engine_type": "uint", "params": { "size": 1, "offset": 3, "min": 1, "max": 255, "op": "inc", "step": 1, } }, { "engine_name": "nbar2HttpHost", "engine_type": "histogram_url", "params": { "size": 60, "offset": 0, "entries": [ { "schemes": ["https"], "hosts": ["google.com"], "random_queries": true, "prob": 5 }, { "schemes": ["ftp"], "hosts": ["downloads.cisco.com", "software.cisco.com"], "paths": ["ios-xe", "nx-os"], "queries": ["version=16", "version=7"], "prob": 2 }, { "schemes": ["http", "https"], "hosts": ["trex-tgn.cisco.com"], "paths": ["doc", "releases", "sdk"], "prob": 3 } ] } } ] }, { "name": "mix2", "auto_start": true, "rate_pps": 0.5, "data_records_num": 5, "template_id": 266, "fields": [ { "name": "ipVersion", "type": 60, "length": 1, "data": [4] }, { "name": "flowStartSysUpTime", "type": 22, "length": 4, "data": [0, 0, 0, 0] }, { "name": "flowEndSysUpTime", "type": 21, "length": 4, "data": [0, 0, 0, 0] } ], "engines": [ { "engine_name": "ipVersion", "engine_type": "histogram_uint", "params": { "size": 1, "offset": 0, "entries": [ { "v": 4, "prob": 3, }, { "v": 6, "prob": 1 } ] } }, { "engine_name": "flowStartSysUpTime", "engine_type": "time_start", "params": { "size": 4, "offset": 0, "time_end_engine_name": "flowEndSysUpTime", "ipg_min": 10000, "ipg_max": 20000, "time_offset": 200000 } }, { "engine_name": "flowEndSysUpTime", "engine_type": "time_end", "params": { "size": 4, "offset": 0, "time_start_engine_name": "flowStartSysUpTime", "duration_min": 5000, "duration_max": 10000, } } ] } ] }
-
netflow_version: Might be 9 or 10, notice that version 9 doesn’t support variable length fields or per enterprise fields. Defaults to 10. -
dst(mandatory): Defines the destination URL to which IPFIX records will be sent. The scheme of the URL is used to determine how records are exported (the exporter type). The following exporter types (schemas) are supported: emu-udp, udp, file, http, and https. If no scheme is specified, emu-udp exporter will be used and the expected string should be of the format host:port. For example,"127.0.0.1:8080"or"[2001:db8::1]:4739". Please refer to IPFix Exporters section below for more information. -
domain_id: The observation domain ID as defined in IPFix. If not provided, it will be randomly generated. -
max_template_records: A limit on the number of template records exported by the IPFix plugin after it is loaded. The default value is zero which means no limit is imposed. -
max_data_records: A limit on the number of data records exported by the IPFix plugin after it is loaded. The default value is zero which means no limit is imposed. -
max_time: Defines a maximum time duration where records are generated and exported by the plugin. The default value is zero which means no limit is imposed. -
auto_start: If true, the client will automatically start sending IPFIX packets upon creation. Otherwise, the user has to manually enable the client using API or console command. The default is true. -
exporter_params: A JSON object that configures the exporter used by the client. The content ofexporter_paramsdepends on the type of the exporter being used. Please refer to IPFix exporters section below for more information. -
generators(mandatory): A list of generators. Each generator defines a Template and operations on that template, like for example the data packets rate. Each generator contains:-
name(mandatory): Name of the generator. This field is required. -
auto_start: If true will automatically start sending IPFix packets upon creation. -
template_rate_pps: Rate of IPFix template packets (in pps), defaults to 1. -
rate_pps: Rate of IPFix data packets (in pps), defaults to 3. -
data_records_num: Number of data records in each data packet. If not provided, it will default to the maximum number of data packets which doesn’t exceed the MTU. -
is_options_template: Indicates if this generator will send Options Template (True) packets or Data Template packets (False). Defaults to False. -
scope_count: Scope count in case of Options Template packets. Must be bigger than 0. -
template_id(mandatory): The template ID for this generator. Must be greater than 255. This field is required. Each generator must have a unique template identifier. -
fields(mandatory): List of fields for this generator. Fields are very much alike the fields of Netflow. Each field is represented by a dictionary.-
name(mandatory): Name of this field. The name is required. -
type(mandatory): A uint16 that is unique per type. One can consult the RFC for specific values of types. -
length(mandatory): Length of this field in bytes. If the value is 0xFFFF, this indicates variable length fields. Variable length fields are not supported at the moment. Variable lengths are supported only in v10. -
enterprise_number: Enterprise number in case the field is specific per enterprise and the type’s MSB equals 1 to indicate this is an enterprise field. Enterprise fields are supported only in v10. -
data: List of bytes of size length. This will be the initial data in data packets and can be modified by the engines.
-
-
engines: List of engines as described in the previous sections. This field is not mandatory in case we don’t want to modify any data. However it is important that the name of each engine should be a field name, and the offset is relative to the beginning of that field.
-
3.9.2. IPFix Exporters
The IPFix plugin supports several ways to send the generated template and data records to a collector, namely - exporters. Exporters are defined and configured per client as part of its initialization JSON. The type of exporter to use and destination URL are specified by the "dst" field in the init JSON as explained below.
The exporter_params optional object in the JSON may be used to configure the exporter. All fields of exporter_params are optional. If a given field is not specified, its default value will be used.
|
|
In order to use the kernel-level exporters - the emu-server must run in kernel mode as follows: bin$ ./trex-emu -kor bin$ ./trex-emu --kernel-modeThe kernel-level exporters are udp, file, http, and https |
The following exporter types are supported:
EMU-UDP
This exporter type configures the client to send IPFIX UDP packets built in the application layer using TREX. The IPfix records are aggregated up to MTU size and the resulting UDP packet is sent to the specified IP:PORT destination.
There are two ways to define it using the "dst" field:
-
“host:port”– host:port URL without scheme will use EMU-UDP exporter. Examples:"10.56.216.158:8080"or"[2001:db8::1]:4739". -
"emu-udp://host:port"– you can also specify the scheme explicitly. Example:“emu-udp://10.56.216.158:8080”
UDP
In this case flow records are sent using GoLang UDP sockets library utilizing the OS kernel. Records are aggregated up to MTU size and sent to the specified IP:PORT destination.
"dst" field should be specified as follows - "udp://host:port".
Example: “udp://10.56.216.158:8080”
"exporter_params": { "use_emu_client_ip_addr": false, "raw_socket_interface_name": "lo" },
-
use_emu_client_ip_addr(default: false): If false the source IP address of the UDP connection will be the host’s address as set by the OS. If true, the source IP address will be set to be the EMU client’s IPv4 address, if it exist. Enabling this option requires EMU server to run as root. Otherwise, IPFIX plugin creation will fail. -
raw_socket_interface_name(default: lo): Name of the interface to use to bind raw-sockets whenuse_emu_client_ip_addris enabled. If not defined, the UDP exporter will use the localhost interface ("lo").
FILE
This exporter type stores generated flow records in files in a user-defined directory. The generated records are aggregated in a single file up to a max size and for max interval duration. Once the file aggregation reaches either of these limits, it will be ‘rotated’ – closed and compressed with a unique name in the same directory.
There is also an option to limit the max number of files created in the directory. Once the maximum number of files is reached - old (rotated) files may be deleted. "dst" field should be specified as follows - “file://dir/name”.
Example: “file:///auto/avc-devtest/tmp/obarash/trex-emu/fnf_agg.ipfix”.
File URL will use the file exporter with the given dir/name path.
dir/name can be also specified explicitly in the exporter_params object.
"exporter_params": { "name": "fnf_agg.ipfix", "dir": "/scratch/myproject", "max_size": 1048576, "max_interval": "15s", "max_files": 100, "compress": true, "input_channel_capacity": 500 }
|
|
There is no need to specify name and dir params explicitly - if it is not defined it will be derived from "dst" field. |
-
name(default: fnf_agg.ipfix): The filename to write flow records to. Name structure is “base.ext”. In the example base is ‘fnf_agg’ and ext is ‘ipfix’. The name of rotated files is of the form –<base>_<index>.<start-timestamp>-<end-timestamp>.<ext>.gzExample:fnf_agg_1.20220603084739-20220603084839.ipfix.gz -
dir(default: empty string): The path in which export files are created. If empty string (the default) is configured the exporter will use the OS temp directory (/tmp). The exporter of each client will have a separate unique folder under dir path with the following name –<base>_<pid>_<mac>.<ext>(<pid> is the process’s id) Example:fnf_agg_129399_000000700003.ipfix(where 129399 is the process id). As an example, suppose the user’s directory is ‘/scratch/myproject’, name is ‘fnf_agg.ipfix’ and we have 2 clients - 01:01:01:01:01:01 and 02:02:02:02:02:02. Files will be created in two separate folders -/scratch/myproject/fnf_agg_129399_010101010101.ipfix/fnf_agg_1.20220603084739-20220603084839.ipfix.gzand/scratch/myproject/fnf_agg_129399_020202020202.ipfix/fnf_agg_1.20220603084739-20220603084839.ipfix.gz -
max_size(default: 1048576): The maximum size in bytes of the export file before it gets rotated. Once the file gets to this size it will be immediately rotated. Value of zero means no limit on the size. -
max_interval(default: 60s): The maximum time duration in seconds where IPFix records can be aggregated to a file before it is rotated. The parameter’s value type can be:-
Integer - Holding the time duration in nanoseconds.
-
String - The time duration is represented as a Go time.Duration string type. In the example max_interval is "15s" and so a file will be exported every 15 seconds (unless it reached max_size faster).
-
-
max_files(default: 100): The maximum number of old rotated files to retain. Value of zero means to retain all rotated files. -
compress(default: true): Determines if the rotated files should be compressed using gzip. -
input_channel_capacity(default: 10000): The maximum size of the input queue. This can be lowered to reduce memory consumption in case of a large number of EMU clients and low records rate per client.
HTTP/HTTPS
HTTP exporter is based on an underlying file exporter to temporarily aggregate flow records in files. Once a file is rotated, an HTTP or HTTPS post request will be created and sent to the user-defined URL. The temporary file will be deleted after the post request transaction is completed (either with success or failure).
"dst" field should be specified as follows - “http://host:port/path”.
Example: “http://10.56.216.158:8080/api/ipfixfilecollector/exalt-tenant/site9999/device10/post_file”.
Rotated files will be sent to the destination URL using HTTP/HTTPS.
"exporter_params": { "name": "fnf_agg.ipfix", "url": "http://10.56.216.158:8080/api/ipfixfilecollector/exalt-tenant/site9999/device10/post_file" "dir": "/scratch/myproject", "max_size": 1048576, "max_interval": "15s", "max_files": 100, "max_posts": 0, "compress": true, "tls_cert_file": "", "tls_key_file": "", "store_exported_files_on_disk": false, "input_channel_capacity": 500 "repeats_num": 15 "repeats_wait_time": "1s" }
|
|
|
-
url: Defines the POST reaquest URL path to which export files are sent. If not defined, uses URL path from dst field. -
tls_cert_file(default: “”): The location of the certificate file for HTTPS. -
tls_key_file(default: “”): The location of the private key file for HTTPS. -
store_exported_files_on_disk(default: false): If true exported files are not deleted from disk. Otherwise, exported files are removed after they are sent. -
repeats_num(default: 1): Number of times to repeat each file export. -
repeats_wait_time(default: "0s"): Time to wait between file repeats. In the example, each file export will be repeated 15 times with 1 second between each repeat.
3.9.3. Netflow example
Let us show an example with the previous JSON we just saw. First we build a Python profile like this:
from trex.emu.api import * import argparse class Prof1(): def __init__(self): self.mac = Mac('00:00:00:70:00:03') self.def_ns_plugs = {'arp': {'enable': True}, 'ipv6' : {'dmac':self.mac.V()}} self.def_c_plugs = {'arp': {'enable': True}} def create_profile(self, is_ipv6, mac, ipv4, ipv6, dg_4, dst_ipv4, dst_ipv6, dst_port): mac = Mac(mac) ipv4 = Ipv4(ipv4) dg_4 = Ipv4(dg_4) ipv6 = Ipv6(ipv6) host_port = HostPort(dst_ipv6, dst_port) if is_ipv6 else HostPort(dst_ipv4, dst_port) ns_key = EMUNamespaceKey(vport = 0, tci = 0,tpid = 0) ns = EMUNamespaceObj(ns_key = ns_key, def_c_plugs = self.def_c_plugs) c = EMUClientObj(mac = mac.V(), ipv4 = ipv4.V(), ipv6 = ipv6.V(), ipv4_dg = dg_4.V(), plugs = {'ipfix': self.get_init_json(host_port),'arp': {'enable': True}, 'ipv6': {}}) ns.add_clients(c) return EMUProfile(ns = [ns], def_ns_plugs = self.def_ns_plugs) def get_profile(self, tuneables): # Argparse for tunables parser = argparse.ArgumentParser(description='Argparser for simple_ipfix.py', formatter_class=argparse.ArgumentDefaultsHelpFormatter) # client args parser.add_argument('--is_ipv6', action = 'store_true', dest = 'is_ipv6', help="IPv6 traffic?") parser.add_argument('--mac', type = str, default = '00:00:00:70:00:03', help='Mac address of the client.') parser.add_argument('--4', type = str, default = '1.1.1.3', dest = 'ipv4', help='IPv4 address of the client.') parser.add_argument('--6', type = str, default = '2001:DB8:1::2', dest = 'ipv6', help='IPv6 address of the client.') parser.add_argument('--dg-4', type = str, default = '1.1.1.1', help='IPv4 Address of the Default Gateway.', dest = 'dg_4') parser.add_argument('--dst-4', type = str, default = '10.56.97.19', dest = 'dst_4', help='IPv4 address of collector') parser.add_argument('--dst-6', type = str, default = '2001:DB8:3::1', dest = 'dst_6', help='IPv6 address of collector') parser.add_argument('--dst-port', type = str, default = '4739', dest = 'dst_port', help='Destination Port.') args = parser.parse_args(tuneables) return self.create_profile(args.is_ipv6, args.mac, args.ipv4, args.ipv6, args.dg_4, args.dst_4, args.dst_6, args.dst_port) def register(): return Prof1()
For brevity purposes we have omitted the get_init_json function from here but it returns exactly the JSON we saw. In this line we instruct the client that it runs the IPFix plugin with the parameters in the JSON.
|
We can load this profile through the console:
trex>emu_load_profile -f emu/simple_ipfix.py
Now let us see the PCAP generated. In this first picture we see that the client has two generators, the first one with template_id = 261 and Options-Template and the second one with template_id = 266 and Data-Template.
The Data packets for the first generator are generated with a rate of 1 pps, as specified in the init JSON. Meanwhile the Data packets for the second generator are generated with a rate of 0.5 pps. The domain identifier was specified to 7777
in the init JSON, but be careful not to create 2 clients with the same domain identifier. Options-Template and Data-Template packets are send with a default rate of 1 pps but this can be altered through the template_rate_pps value in the init JSON
or through the console API which we will explore soon.
We can have a closer look at the Options Template packet and see that we have three fields as specified, the first and third being Cisco enterprise fields and the second one being the protocol identifier. The scope is 1 as specified in the init JSON.
Next, we take a closer look at the Data Template packet and see that it has 3 fields, IP version and the flowStartSysUpTime, flowEndSysUpTime fields.
Finally, let us see how the data fields change thanks to the engine. Take a look at the engines definition in the init JSON. The first engine, named clientIPv4Address modifies the last byte of this IP address by incrementing it on each record. The first three bytes will remain unchanged from the data parameter provided in the init JSON, hence will remain [16, 0, 0] or [10, 0, 0] in hexadecimal representation. The second engine generates URLs.
And indeed in the first packet which has two flows (specified in the init JSON with data_records_num) we see that the last byte of the client IPv4 address is incremented. We also note that the first URL generated was with a random query, and the second one from the TRex website.
Pay attention that the profile has many parameters (tunables) that can be tuned through the emu_load_profile command. We can see these parameters in the Python cod, such as ipv6, dst_4, dst_6, dst_port.
To see the complete parameters use:
trex>emu_load_profile -f emu/simple_ipfix.py -t -h
Lastly, we added a convoluted profile with variable length, multiple generators, all types of engines, per enterprise fields etc. This profile was build based on the Netflow captures of the Application Visibility and Control (AVC) team here at Cisco. To run this profile, please use:
trex>emu_load_profile -f emu/avc_ipfix.py
The caps contained multiple Netflow Domain Identifiers but the test simulates only 1 client, hence 1 domain identifier at a time. To choose between the domain identifiers, one can make use of the tunables. For example:
trex>emu_load_profile -f emu/avc_ipfix.py -t --domain_id 1024
Other parameters, such as the Netflow destination address/port or URL can also be changed through the tunables.
The list of available tunable parameters can be shown using --help:
emu>emu_load_profile -f emu/avc_ipfix.py -t --help usage: trex_console.py [-h] [--mac MAC] [--4 IPV4] [--dg DG] [--dst-4 DST_4] [--dst-port DST_PORT] [--dst-url DST_URL] [--domain-id DOMAIN_ID] Argparser for AVC IPFix optional arguments: -h, --help show this help message and exit --mac MAC Mac address of the client (default: 00:00:00:70:00:03) --4 IPV4 IPv4 address of the client (default: 1.1.1.3) --dg DG Default Gateway address of the clients. (default: 1.1.1.1) --dst-4 DST_4 Ipv4 address of collector (default: 10.56.29.228) --dst-port DST_PORT Destination port (default: 2055) --dst-url DST_URL Destination URL for HTTP/HTTPS exporter (default: None) --domain-id DOMAIN_ID Domain ID. Registered domain IDs are {6, 256, 512, 768, 1024} (default: 256) 4.13 [ms]
For example, you can set the destination URL using the --dst-url tunable parameter.
The following example shows how to create an avc_ipfix.py profile using HTTP exporter.
emu>emu_load_profile -f emu/avc_ipfix.py -t --dst-url http://127.0.0.1:18088/api/ipfixfilecollector/exalt-tenant/site9999/device10/post_file Converting file to profile [SUCCESS] Converting profile took: 16.66 [ms] Removing old emu profile [SUCCESS] Sending emu profile [SUCCESS] Sending profile took: 23.76 [ms] 42.69 [ms]
3.9.4. IPFIX namespace plugin - devices auto trigger
EMU also supports an option to automatically generate a large number of devices at the namespace level based on a predefined IPFIX plugin. It enables users to easily create a multi-device IPFIX profile which can scale to a large number of devices. This profile can be used instead of creating each device individually. The devices are created gradually over the course of a user-defined ramp-up time.
Terminology
Let us first define more concretely some terms we are using:
-
Device – this is an IPFIX device which generates records and exports them. In our model, each device is associated with some EMU-client and holds one exporter which can be UDP or HTTP. Devices are identified internally in EMU by their MAC and IP addresses.
-
Tenant – multi-tenancy is used to separate groups of devices (especially in cloud-delivered deployments). A tenant is identified by its tenant-id. Each device belongs to one tenant. A tenant may contain 1 or more devices.
-
UDP – multi-tenancy is not supported.
-
HTTP – tenants are identified by the tenant-id in the POST DST URL (tenant-id/site-id/device-id).
-
-
Client – a node in the network which creates flows that are captured and exported as data records by the IPFIX device. Clients are identified by their source address (IP_SRC_ADDR [8]) field in the IPFIX data record.
-
App – Applications used by a client. Apps are identified by their APPLICATION_ID [95] field in the IPFIX data record.
Configuration
|
|
|
Configuring devices auto-trigger feature is done via the namespace level init JSON as shown in the following example:
{ "def_ns_plugs": {}, "namespaces": [ { "vport": 0, "tci": [ 0 ], "tpid": [ 0 ], "plugs": { "ipfix": { "devices_auto_trigger": { "device_mac": "00:00:00:70:00:02", "device_ipv4": "1.1.1.1", "devices_num": 10000, "device_domain_id": 1, "rampup_time": "5m", "sites_per_tenant": 1, "devices_per_site": 1, "total_rate_pps": 20000, "clients_generator": { "client_ipv4_field_name": "clientIPv4Address", "client_ipv4": [1,1,1,1], "clients_per_device": 48, "data_records_per_client": 41 }, "device_init": { "netflow_version": 10, "dst": "http://127.0.0.1:18088/api/ipfixfilecollector/tenant-%t/site-%s/device-%d/post_file", "domain_id": 16777217, "auto_start_after": "2s", "exporter_params": { <<snip>> }, "generators": <<snip>> } } } }, "def_c_plugs": {}, "clients": [] } ] }
-
device_init(mandatory): A fully-fledged IPFIX plugin initialization JSON. It describes the IPFIX configuration of each created device. -
devices_num(mandatory): Number of devices to automatically create. -
device_mac(mandatory): MAC address of the first device to be created. The MAC address of consecutive devices will increment starting from this MAC. -
device_ipv4(mandatory): IPv4 address of the first device to be created. The MAC address of consecutive devices will increment starting from this IP. -
device_domain_id(default: 0): domain-id of the first devices to be created. The domain-id of consecurive devices will increment starting from this domain-id. If this field is zero it will be ignored and the domain-id will be determined from device_init JSON. -
rampup_time(default: ‘1s’): The time interval over which the devices are gradually triggered at a rate of<rampup_time>/<num_devices>devices per second. -
sites_per_tenant(default: 0): Number of sites per tenant. Tenant ID will increment modulo this value. Value of zero means that tenant ID will not change. -
devices_per_site(default: 0): Number of devices per site. Site ID will incitement modulo this value. Value of zero means that site ID will not change. -
total_rate_pps: Defines the total rate of the data records from all devices. The rate of data records will be normalized and then scaled by a factor of<total_rate_pps>/<num_devices>. Note that this scaling applies only to flows data records. The rate of options templates, data templates, and options data records will not be affected (we assume that these packets are sent only once or in a very slow rate). -
clients_generator: This section configures EMU to dynamically generate client IPs which are unique across all triggered devices. In this example, each device will be assigned a range of 48 client IPs which are repeated 41 times in a round-robin fashion. This configuration results in 48*41 client-app unique combinations for each device. The total number of unique “4T+App+Exp+Obs” keys for all devices is thus 48*41*10000.
Tenant/Site/Device Ids
Each triggered device is given IDs based on devices_per_site and sites_per_tenant configuration parameters. The DST URL can optionally contain embedded format specifiers that are replaced by the values of the corresponding Id. Following is the list of Ids associated with each triggered devices and its format specifier:
-
Tenant Id(specifier:%t): Tenant Id starting from zero and increments after eachsites_per_tenant. -
Tenant UUID(specifier:%Ut): UUID corresponding to each tenant Id. -
Site Id(specifier:%s): Site Id modulosites_per_tenantstarting from zero and increments after eachdevicesPerSitedevices. -
Site UUID(specifier:%Us): UUID corresponding to each site Id. -
Device Id(specifier:%d): Device Id modulodevices_per_sitestarting from zero and incremented for each device. -
Device UUID(specifier:%Ud): UUID corresponding to each device Id. -
UUID(specifier:%u): UUID unique for each triggered device.
Example:
Suppose we have sites_per_tenant = 2, devices_per_site = 3, and the DST URL is defined with the following format - tenant-%Ut-%t/site-%Us-%s/device-%Ud-%d.
The following URLs will be generated for 18 devices:
tenant-ff454036-b7fa-411a-8e02-24d01dd830dd-0/site-a43ed1a2-b0c2-471f-946f-35068d635405-0/device-21c1012e-2bd2-43ad-9d49-92915c5a6651-0
tenant-ff454036-b7fa-411a-8e02-24d01dd830dd-0/site-a43ed1a2-b0c2-471f-946f-35068d635405-0/device-bfa18cad-00f1-4983-9b3a-7235f2d7efac-1
tenant-ff454036-b7fa-411a-8e02-24d01dd830dd-0/site-a43ed1a2-b0c2-471f-946f-35068d635405-0/device-0955928e-e78d-4ae9-80f3-90be4010bfdf-2
tenant-ff454036-b7fa-411a-8e02-24d01dd830dd-0/site-18805fee-d17e-4a9d-8adc-bbf91805e51c-1/device-21c1012e-2bd2-43ad-9d49-92915c5a6651-0
tenant-ff454036-b7fa-411a-8e02-24d01dd830dd-0/site-18805fee-d17e-4a9d-8adc-bbf91805e51c-1/device-bfa18cad-00f1-4983-9b3a-7235f2d7efac-1
tenant-ff454036-b7fa-411a-8e02-24d01dd830dd-0/site-18805fee-d17e-4a9d-8adc-bbf91805e51c-1/device-0955928e-e78d-4ae9-80f3-90be4010bfdf-2
tenant-f04f5225-9045-44aa-b40a-a8876b26044b-1/site-a43ed1a2-b0c2-471f-946f-35068d635405-0/device-21c1012e-2bd2-43ad-9d49-92915c5a6651-0
tenant-f04f5225-9045-44aa-b40a-a8876b26044b-1/site-a43ed1a2-b0c2-471f-946f-35068d635405-0/device-bfa18cad-00f1-4983-9b3a-7235f2d7efac-1
tenant-f04f5225-9045-44aa-b40a-a8876b26044b-1/site-a43ed1a2-b0c2-471f-946f-35068d635405-0/device-0955928e-e78d-4ae9-80f3-90be4010bfdf-2
tenant-f04f5225-9045-44aa-b40a-a8876b26044b-1/site-18805fee-d17e-4a9d-8adc-bbf91805e51c-1/device-21c1012e-2bd2-43ad-9d49-92915c5a6651-0
tenant-f04f5225-9045-44aa-b40a-a8876b26044b-1/site-18805fee-d17e-4a9d-8adc-bbf91805e51c-1/device-bfa18cad-00f1-4983-9b3a-7235f2d7efac-1
tenant-f04f5225-9045-44aa-b40a-a8876b26044b-1/site-18805fee-d17e-4a9d-8adc-bbf91805e51c-1/device-0955928e-e78d-4ae9-80f3-90be4010bfdf-2
tenant-7427783f-e01f-4257-b1af-217124aeb84a-2/site-a43ed1a2-b0c2-471f-946f-35068d635405-0/device-21c1012e-2bd2-43ad-9d49-92915c5a6651-0
tenant-7427783f-e01f-4257-b1af-217124aeb84a-2/site-a43ed1a2-b0c2-471f-946f-35068d635405-0/device-bfa18cad-00f1-4983-9b3a-7235f2d7efac-1
tenant-7427783f-e01f-4257-b1af-217124aeb84a-2/site-a43ed1a2-b0c2-471f-946f-35068d635405-0/device-0955928e-e78d-4ae9-80f3-90be4010bfdf-2
tenant-7427783f-e01f-4257-b1af-217124aeb84a-2/site-18805fee-d17e-4a9d-8adc-bbf91805e51c-1/device-21c1012e-2bd2-43ad-9d49-92915c5a6651-0
tenant-7427783f-e01f-4257-b1af-217124aeb84a-2/site-18805fee-d17e-4a9d-8adc-bbf91805e51c-1/device-bfa18cad-00f1-4983-9b3a-7235f2d7efac-1
tenant-7427783f-e01f-4257-b1af-217124aeb84a-2/site-18805fee-d17e-4a9d-8adc-bbf91805e51c-1/device-0955928e-e78d-4ae9-80f3-90be4010bfdf-2
devices_auto_trigger_ipfix.py
The EMU client console provides a predefined profile file named devices_auto_trigger_ipfix.py. This file can be used to create IPFIX devices auto-trigger namespace level profile as described above.
emu>emu_load_profile -f emu/devices_auto_trigger_ipfix.py -t --help usage: trex_console.py [-h] [--domain-id DOMAIN_ID] [--dst-url DST_URL] [--device-mac DEVICE_MAC] [--device-ipv4 DEVICE_IPV4] [--devices-num DEVICES_NUM] [--rampup-time RAMPUP_TIME] [--sites-per-tenant SITES_PER_TENANT] [--devices-per-site DEVICES_PER_SITE] [--total-rate-pps TOTAL_RATE_PPS] [--max-template-records MAX_TEMPLATE_RECORDS] [--max-data-records MAX_DATA_RECORDS] [--exporter-max-interval EXPORTER_MAX_INTERVAL] [--exporter-max-size EXPORTER_MAX_SIZE] [--exporter-max-posts EXPORTER_MAX_POSTS] [--exporter-compressed | --no-exporter-compressed] [--exporter-store-exported-files-on-disk | --no-exporter-store-exported-files-on-disk] [--exporter-repeats-num EXPORTER_REPEATS_NUM] [--exporter-repeats-wait-time EXPORTER_REPEATS_WAIT_TIME] Argparser for IPFIX devices auto generation (triggering) optional arguments: -h, --help show this help message and exit --domain-id DOMAIN_ID Domain ID. Registered domain IDs are {6, 256, 512, 768, 1024} (default: 256) --dst-url DST_URL Exporter destination URL (default: udp://127.0.0.1:18088) --device-mac DEVICE_MAC Mac address of the first device to be generated (default: 00:00:00:70:00:03) --device-ipv4 DEVICE_IPV4 IPv4 address of the first device to be generated (default: 1.1.1.3) --devices-num DEVICES_NUM Number of devices to generate (default: 1) --rampup-time RAMPUP_TIME The time duration over which the devices should be generated (default: None) --sites-per-tenant SITES_PER_TENANT Number of sites per tenant (default: None) --devices-per-site DEVICES_PER_SITE Number of devices per site (default: None) --total-rate-pps TOTAL_RATE_PPS The total rate (pps) in which all devices export IPFIX packets (default: None) --max-template-records MAX_TEMPLATE_RECORDS Max template records to send. Value of 0 means no limit (default: None) --max-data-records MAX_DATA_RECORDS Max data records to send. Value of 0 means no limit (default: None) --exporter-max-interval EXPORTER_MAX_INTERVAL HTTP exporter max interval to wait between two consecutive posts (default: None) --exporter-max-size EXPORTER_MAX_SIZE HTTP exporter max size of files to export (default: None) --exporter-max-posts EXPORTER_MAX_POSTS HTTP exporter max posts to export (default: None) --exporter-compressed, --no-exporter-compressed HTTP exporter store exported files on disk (default: None) --exporter-store-exported-files-on-disk, --no-exporter-store-exported-files-on-disk HTTP exporter store exported files on disk (default: None) --exporter-repeats-num EXPORTER_REPEATS_NUM HTTP exporter number of times to repeat each export (default: None) --exporter-repeats-wait-time EXPORTER_REPEATS_WAIT_TIME HTTP exporter time to wait between repeats (default: None)
dnac_scale_test_ipfix.py
The EMU client console provides a predefined profile file named dnac_scale_test_ipfix.py. This profile is based on IPFIX devices auto-triggering capability in order to send traffic pattern which is essentially the same as the standard DNAC Scale Test legacy Python script.
emu>emu_load_profile -f emu/dnac_scale_test_ipfix.py -t --help usage: trex_console.py [-h] [--dst-ipv4 DST_IPV4] [--dst-port DST_PORT] [--device-mac DEVICE_MAC] [--device-ipv4 DEVICE_IPV4] [--devices-num DEVICES_NUM] [--rampup-time RAMPUP_TIME] [--total-rate-pps TOTAL_RATE_PPS] [--client-ipv4 CLIENT_IPV4] [--clients-per-device CLIENTS_PER_DEVICE] [--apps-per-client APPS_PER_CLIENT] [--exporter-use-emu-client-ip-addr USE_EMU_CLIENT_IP_ADDR] [--exporter-raw-socket-interface-name RAW_SOCKET_INTERFACE_NAME] Argparser for IPFIX DNAC scale test optional arguments: -h, --help show this help message and exit --dst-ipv4 DST_IPV4 Ipv4 address of collector (default: 127.0.0.1) --dst-port DST_PORT Destination port (default: 18088) --device-mac DEVICE_MAC Mac address of the first device to be generated (default: 00:00:00:70:00:01) --device-ipv4 DEVICE_IPV4 IPv4 address of the first device to be generated (default: 128.1.1.1) --devices-num DEVICES_NUM Number of devices to generate (default: 4000) --rampup-time RAMPUP_TIME The time duration over which the devices should be generated (default: 1s) --total-rate-pps TOTAL_RATE_PPS The total rate (pps) in which all devices export IPFIX packets (default: 25000) --client-ipv4 CLIENT_IPV4 The total rate (pps) in which all devices export IPFIX packets (default: 1.1.1.1) --clients-per-device CLIENTS_PER_DEVICE The total rate (pps) in which all devices export IPFIX packets (default: 48) --apps-per-client APPS_PER_CLIENT The total rate (pps) in which all devices export IPFIX packets (default: 41) --exporter-use-emu-client-ip-addr USE_EMU_CLIENT_IP_ADDR UDP exporter use EMU client IP addr (default: None) --exporter-raw-socket-interface-name RAW_SOCKET_INTERFACE_NAME UDP exporter raw socket interface name to use if use-emu-client-ip-addr is set (default: None)
"ipfix": { "devices_auto_trigger": { "device_mac": [0,0,0,70,0,1], "device_ipv4": [128,1,1,1], "devices_num": 4000, "rampup_time": "1s", "total_rate_pps": 25000, "clients_generator": { "client_ipv4_field_name": "clientIPv4Address", "client_ipv4": [1,1,1,1], "clients_per_device": 48, "data_records_per_client": 41 }, "device_init": { "netflow_version": 10, "dst": "udp://127.0.0.1:4511/", "domain_id": 256, "max_template_records": 1, "exporter_params": { "use_emu_client_ip_addr": true }, <<snip>> } } }
-
4000 devices are triggered immediately (ramped up in the first second).
-
Overall PPS rate for all devices is ~25K.
-
“use_emu_client_ip_addr” field in UDP’s exporter params section configures the exporter of each device to use its IPv4 address as the source IP instead of the address of the host machine. The default is false.
-
“clients_generator” section configures EMU to dynamically generate client IPs which are unique across all triggered devices. In this example, each device will be assigned a range of 48 client IPs which are repeated 41 times in a round-robin fashion. This configuration results in 48*41 client-app unique combinations for each device to get a total of 48*41*4000 active “4T+App+Exp+Obs” keys in the main aggregator.
emu_ipfix_show_ns_counters
The console command emu_ipfix_show_ns_counters can be used to show IPFIX namespace counters:
emu_ipfix_show_ns_counters - Show IPFix namespace counters
Example:
emu>emu_load_profile -f emu/devices_auto_trigger_ipfix.py -t --rampup-time 30s --devices-num 60 Converting file to profile [SUCCESS] Converting profile took: 3.88 [ms] Removing old emu profile [SUCCESS] Sending emu profile [SUCCESS] emu>emu_ipfix_show_ns_counters -p 0 Devices Auto Trigger Counters name | value -----------------+------ rampupTime | 30 rampupTimeSoFar | 19 devicesToTrigger | 60 devicesTriggered | 38
3.9.5. Netflow/IPFix Console API
Last in this section we explore the Netflow/IPFix console API. We have the following functions:
emu_ipfix_disable_gen - Disable an IPFix generator. emu_ipfix_enable_gen - Enable an IPFix generator. emu_ipfix_get_exp_info - Get IPFix exporter information. emu_ipfix_get_gen_info - Get IPFix generators information. emu_ipfix_set_data_rate - Set IPFix generator data rate. emu_ipfix_set_template_rate - Set IPFix generator template rate. emu_ipfix_show_counters - Show IPFix data counters data. emu_ipfix_show_ns_counters - Show IPFix namespace counters
We can get information on a client, for example:
trex(service-filtered)>emu_ipfix_get_gen_info -p 0 --mac 00:00:00:70:00:03 Generators Name | Temp. ID | Enabled | Opt. Temp. | Scope cnt | Temp. Rate | Data Rate | Records spec. -----+----------+---------+------------+-----------+------------+-----------+--------------- mix2 | 266 | True | False | 0 | 1 | 0.500 | 5 mix1 | 261 | True | True | 1 | 1 | 1 | 2 | Records calc. | Fields | Engines +---------------+--------+--------- | 5 | 3 | 3 | 2 | 3 | 2
Let us see the counters:
trex(service-filtered)>emu_ipfix_show_counters -p 0 --mac 00:00:00:70:00:03 Ipfix Counters name | value ------------------------+------ pktTempSent | 170 pktDataSent | 127 socketWriteError* | 5 6.65 [ms]
We can change the data rate of any generator, for example:
trex>emu_ipfix_set_data_rate -p 0 --mac 00:00:00:70:00:03 -g mix2 -r 1000 7.19 [ms]
After changing we can see the counters and see that we are sending a lot of packets:
trex(service-filtered)>emu_ipfix_show_counters -p 0 --mac 00:00:00:70:00:03 --zero Ipfix Counters name | value -------------------------+------ pktTempSent | 458 pktDataSent | 25790 templatePktLongerThanMTU | 0 recordsMtuMissErr* | 0 dataIncorrectLength* | 0 invalidSocket* | 0 socketWriteError* | 5 invalidJson* | 0 failedCreatingGen* | 0 invalidDst* | 0 enterpriseFieldv9* | 0 variableLengthFieldv9* | 0 variableLengthNoEngine* | 0 badOrNoInitJson* | 0 duplicateGenName* | 0 duplicateTemplateID* | 0 invalidTemplateID* | 0 failedBuildingEngineMgr* | 0 invalidEngineName* | 0 invalidScopeCount* | 0 9.75 [ms]
The command emu_ipfix_get_exp_info shows information specific to the exporter.
To demonstrate this, let us load the IPFix plugin with an HTTP exporter as follows:
emu>emu_load_profile -f emu/avc_ipfix.py -t --dst-url http://127.0.0.1:18088/api/ipfixfilecollector/exalt-tenant/site9999/device10/post_file Converting file to profile [SUCCESS] Converting profile took: 16.66 [ms] Removing old emu profile [SUCCESS] Sending emu profile [SUCCESS] Sending profile took: 23.76 [ms] 42.69 [ms]
You can now use emu_ipfix_get_exp_info to show info about the most recently exported files by the EMU client.
For each file export attemp it shows:
-
Name: The name of the file. -
Time: The local time of when the export was done. -
Status: Was the file exported successfully? A success means that we got a positive reply from the collector (HTTP 200 OK). A failure to export can be caused either by a tranport error or HTTP error. -
Trans Status: The transport status - if failed it means that no connection coule be established with the collector’s HTTP server. -
HTTP Status: The HTTP status code as received from the collector. -
HTTP Response Message: A textual representation of the HTTP status code. -
Bytes Uploaded: The number of bytes uploaded to the collector by the file in case of success, or zero otherwise. -
Temp Records Uploaded: The number of template records uploaded to the collector by the file in case of success, or zero otherwise. -
Data Records Uploaded: The number of data records uploaded to the collector by the file in case of success, or zero otherwise.
You can also use emu_ipfix_show_counters to get the exporter’s counters on top of the general plugin counters. In the example below you can see counters for both HTTP and FILE exporters since the HTTP exporter enables and implicitly runs on top of a FILE exporter.
emu>emu_ipfix_show_counters -p 0 --mac 00:00:00:70:00:03 --zero Ipfix Http Exporter Counters name | value -----------------------+--------- writes | 13635 writesFailed | 0 txBytes | 14601600 filesExported | 21 filesExportFailed | 5 filesExportFailedRetry | 0 filesExportRetry | 0 failedToCreateRequest | 0 failedToSendRequest | 5 httpStatus2xx | 21 httpStatus3xx | 0 httpStatus4xx | 0 httpStatus5xx | 0 bytesUploaded | 3160725 tempRecordsUploaded | 107 dataRecordsUploaded | 107110 maxPosts | 0 maxPostsExceeded | 0 Ipfix File Exporter Counters name | value -----------------------+--------- writes | 13635 writesFailed | 0 txBytes | 14601600 filesExported | 0 filesExportFailed | 0 cmdChanEvLowWatermark | 0 cmdChanEvHighWatermark | 0 evFileCreated | 26 evFileRemoved | 0 cmdWrite | 13635 cmdTimerTick | 26 cmdRotate | 26 maxFilesExceeded | 0 fileRotates | 26 fileRotatesFailed | 0 Ipfix Counters name | value ---------------------------------------+------- pktTempSent | 135 pktDataSent | 13500 recordsTempSent | 135 recordsDataSent | 135000 maxTempRecordsToSend | 0 maxDataRecordsToSend | 0 templatePktLongerThanMTU | 0 recordsMtuMissErr* | 0 dataIncorrectLength* | 0 failedCreatingExporter* | 0 failedCreatingExporterWrongKernelMode* | 0 exporterWriteError* | 0 genPausedSkipWrite | 0 invalidJson* | 0 failedCreatingGen* | 0 invalidDst* | 0 enterpriseFieldv9* | 0 variableLengthFieldv9* | 0 variableLengthNoEngine* | 0 badOrNoInitJson* | 0 duplicateGenName* | 0 duplicateTemplateID* | 0 invalidTemplateID* | 0 failedBuildingEngineMgr* | 0 invalidEngineName* | 0 invalidScopeCount* | 0 8.26 [ms]
3.10. Tutorial: Appsim
Appsim plugin provide similar capabilities as ASTF L7 interpreter. The objective is to simulate L7 applications (client and server) on top of a transport layer (tcp/udp). Each client/server could have about ~250 active flows (UDP/TCP).
let’s start with a an example that simulate SSDP notification (IPv4/UDP/HTTP header). it is a multicast address
#simulate SSDP program SSDP_L7 = r'''NOTIFY * HTTP/1.1\r HOST: 239.255.255.250:1900\r CACHE-CONTROL: max-age=120\r lOCATION: http://192.168.1.1:7406/rootDesc.xml\r SERVER: UPnP/Tomato 1.28.7500 MIPSR2Toastman-RT K26 USB Ext UPnP/1.0 MiniUPnPd/1.6\r NT: upnp:rootdevice\r USN: uuid:04645c3d-e6b4-4eea-bd35-5c320c12969f::upnp:rootdevice\r NTS: ssdp:alive\r OPT: "http://schemas.upnp.org/upnp/1/0/";\r 01-NLS: 1\r BOOTID.UPNP.ORG: 1\r CONFIGID.UPNP.ORG: 1337\r ''' NS_PROG = { "buf_list": [ "", "SFRUUC8xLjEgMjAwIE9LDQpTZ" ], "program_list": [ { "commands": [ { "msec": 10, "name": "keepalive" }, { "buf_index": 0, "name": "tx_msg" }, { "min_pkts": 1, "name": "rx_msg" } ] }, { "commands": [ { "msec": 10, "name": "keepalive" }, { "min_pkts": 1, "name": "rx_msg" }, { "buf_index": 1, "name": "tx_msg" } ] } ], "templates": [{ "client_template" :{"program_index": 0, "port": 80, "cps": 1 }, "server_template" : {"assoc": [ { "port": 80 } ], "program_index": 1 } }] } def getNsProgram(): NS_PROG["buf_list"][0]= base64.b64encode(SSDP_L7.encode('ascii')).decode('ascii') return NS_PROG class Prof1(): def __init__(self): self.def_ns_plugs = {'icmp': {}, 'arp' : {'enable': True}, 'transport': {}, 'appsim': getNsProgram() } self.def_c_plugs = {'arp': {'enable': True}, 'icmp': {}, 'transport': {}, } def get_init_json(self, is_server): """Get Init Json for Client :parameters: is_server: bool Indicate if the client is a name server. """ simple_client = { "data" : { "s-1" : { "cps": 1.0, "t": "c", "tid": 0, "ipv6": False, "stream": False, "dst" :"239.255.255.250:1900"}}} # server , cps is not relevant simple_server = { "data" : { "s-1" : { "cps": 1.0, "t": "s", "tid": 0, "ipv6": False, "stream": False, "dst" :"239.255.255.250:1900"}}} return simple_server if is_server else simple_client def create_profile(self, ns_size, clients_size, dns_ipv6): ns_list = [] # create different namespace each time vport, tci, tpid = 0, [0, 0], [0x00, 0x00] for i in range(vport, ns_size + vport): ns_key = EMUNamespaceKey(vport = i, tci = tci, tpid = tpid) ns = EMUNamespaceObj(ns_key = ns_key, def_c_plugs = self.def_c_plugs) mac = Mac('00:00:00:70:00:03') ipv4 = Ipv4('1.1.5.2') ipv6 = Ipv6("2001:DB8:1::3") dns_ip = ipv6.S() if dns_ipv6 else ipv4.S() dg = Ipv4('1.1.5.1') # create a different client each time for j in range(clients_size): client = EMUClientObj(mac = mac[j].V(), ipv4 = ipv4[j].V(), ipv6 = ipv6[j].V(), ipv4_dg = dg.V(), plugs = {'appsim': self.get_init_json(is_server=j==0), 'ipv6': {} } ) ns.add_clients(client) ns_list.append(ns) return EMUProfile(ns = ns_list, def_ns_plugs = self.def_ns_plugs)
The namespace includes the program that is common for all the clients and each client has a streams.
in this case there is one stream base of tid 0 (program 0), client side, ipv4, udp, to dest-ip 239.255.255.250:1900 (multicast)
this will create a udp socket evey 1 second (cps=1) and will send one SSDP UDP packet
for more information about the json format (ns and client) and capabilities have a look into the SDK and into the tests.
To understand the rational behide this engine, it could help to read the ASTF manual
3.11. Tutorial: Load TRex server in multi-core
EMU supports multi-core (STL and ASTF) in software mode, where the filter in done by each DP core, similar to BIRD integration. To run in this mode, do this:
[bash]>sudo ./t-rex-64 -i -c 4 --software --emu
from Console, you should enter service mode filter with mask of emu mode (which will forward all the supported protocols to emu server)
3.12. Python API
Let us see an example of how to the Python API. More can be found on the SDK documentation.
First we need to move the mode to service mode filter to get the packets to EMU (this should be done with TRex server client STL or ASTF)
c_trex = STLClient() c_trex.connect() my_ports=[0,1] c_trex.acquire(ports=my_ports, force=True) c_trex.set_port_attr(promiscuous=True) trex_c.set_service_mode(ports = my_ports, enabled = False, filtered = True, mask = (NO_TCP_UDP_MASK | DHCP_MASK ))
Then we can connect to the EMU server
c = EMUClient(server=EMU_SERVER,
sync_port=4510,
verbose_level= "error",
logger=None,
sync_timeout=None)
# load profile
parser = argparse.ArgumentParser(
description='Simple script to run EMU profile.')
parser.add_argument("-f", "--file", required = True, dest="file",
help="Python file with a valid EMU profile.")
args = parser.parse_args()
c.connect()
print("loading profile from: %s" % args.file)
# start the emu profile
c.load_profile(filename = args.file, max_rate = 2048, tunables = '')
# print tables of namespaces and clients
c.print_all_ns_clients(max_ns_show = 1, max_c_show = 10)
This script assumes there is a TRex-EMU server running on port 4510. It connects and loads a profile with tunables and then prints all the clients.
3.13. Tutorial: Debug tools
Basic debugging can be performed using the following steps:
-
Traces can be taken from the TRex server, the usual way.
-
To debug TRex-EMU using internal packet traces perform the following:
-
Run trex server with
--emu-zmqinstead of--emu. This will just open the zmq channel and not load the emu server -
Open another terminal and run
trex-emu -m | tee /tmp/a.pcap. It will create a file using the k12 packet format.
-
-
To debug the RPC channel, or to see all of the RPC traffic use
trex-emu -v. -
You can even run it remotely, but the order of the following commands is important:
$ sudo ./t-rex-64 -i -c 1 --iom 0 --software --emu-zmq $ trex-emu -m -S {trex-server-ip} | tee /tmp/a.pcap $ trex-console -s {trex-server-ip} --emu --emu-server {emu-server-ip}
3.14. Tutorial: ZMQ transport layer
As previously mentioned in this document, the Emulation server and the Rx Core use a ZeroMQ (ZMQ) channel in order to communicate.
ZMQ offers different flavors of transport, with the classic one being TCP.
However, the most common use case is that the Emulation server and the TRex Core Server run on the same machine, as different processes. If this indeed is the case, we can use IPC as a means of transport.
In our findings, IPC tends to perform better than TCP, because of TCP mechanisms such as congestion control, windowing, etc..
As such, we prefer IPC over TCP. When normally running TRex with the Emulation server, the transport flavor of ZMQ will be IPC.
scripts$ sudo ./t-rex-64 -i -c 1 --iom 0 --software --emu
We can use TCP if we provide the following flag:
scripts$ sudo ./t-rex-64 -i -c 1 --iom 0 --software --emu --emu-zmq-tcp
3.14.1. Tutorial: ZMQ transport layer in debug mode
We remind that the first step to run TRex in debug mode is:
scripts$ sudo ./t-rex-64 -i -c 1 --iom 0 --software --emu-zmq
The TRex server in this case expects the Emulation server to connect using ZMQ with IPC. However, simply running the following command will not work.
scripts/trex_emu$ trex-emu
This is because IPC uses files and for files we need permissions. Hence, in this case we must run
scripts$ sudo taskset -c 0 ./trex-emu
Note that when using TCP in debug mode we don’t need these permissions and we simply can use:
scripts$ sudo ./t-rex-64 -i -c 1 --iom 0 --software --emu-zmq --emu-zmq-tcp scripts/trex_emu$ trex-emu --emu-zmq-tcp
3.15. Tutorial: Profiles with tunables
As you have seen already, most our profiles can be fined tuned with small parameters such as the number of clients or namespaces. This is great and mostly used from the console, however for automated testing it isn’t enough. Automated testing required a finer granularity and the ability to change even the smallest parameters. The Python Api solves this problem, however the purpose of this section is to demonstrate how we can pass some non trivial parameters to the Emu profiles.
- Goal
-
Pass non trivial parameters to Emu profiles.
Let’s look at an DHCP client. In its Init JSON, we can add a dictionary of DHCP Options if we want to override the default options. One such Json can be:
HOSTNAME_DHCP_OPTION = 12 options = { "discoverDhcpClassIdOption": "MSFT 5.0", "requestDhcpClassIdOption": "MSFT 6.0", "dis": [ [HOSTNAME_DHCP_OPTION, ord('j'), ord('s'), ord('o'), ord('n')] ], "req":[ [HOSTNAME_DHCP_OPTION, ord('e'), ord('n'), ord('c'), ord('o'), ord('d'), ord('e')] ], }
|
|
Almost all the parameters we want to tune are part of the Init Json of some plugin, hence being able to pass JSON parameters to profiles solves most of the cases. |
Fortunately for us, Json can be encoded to a string and then decoded back. As such, we can write the following DHCP profile:
def get_profile(self, tuneables): # Argparse for tunables parser = argparse.ArgumentParser(description='Argparser for Dhcp Json Option', formatter_class=argparse.ArgumentDefaultsHelpFormatter) parser.add_argument('--ns', type = int, default = 1, help='Number of namespaces to create') parser.add_argument('--clients', type = int, default = 1, help='Number of clients to create in each namespace') parser.add_argument('--mac', type = str, default = '00:00:00:70:00:01', help='Mac address of the first client') parser.add_argument('--options', type=str, help="A JSON encoded options dictionary.")args = parser.parse_args(tuneables) return self.create_profile(args.ns, args.clients,args.mac, json.loads(args.options))
Add a string parameter for DHCP options.
| |
Decode the string back to Json using json.loads
|
Then we can simply pass the decoded Json to the EmuClient we are creating like this:
client = EMUClientObj(mac = mac[i].V(), ipv4 = ipv4.V(), ipv4_dg = dg.V(), plugs = {'arp': {}, 'icmp': {}, 'igmp': {}, 'dhcp': {'options': options},}, )
options is the decoded Json from the previous snippet.
|
The profile can be loaded very simply using the Native Python Api (also supported in the RPC Proxy) like this:
c.load_profile(profile = PROFILE_PATH, tunables=['--options', json.dumps(options)])
4. Engines
4.1. Intro
Engines are instructions on how to manipulate data on a data buffer. Let’s suppose we have a simple buffer of 4 bytes that represents the application identifier (applicationID ). We could modify
this buffer on a variety of ways such as incrementing/decrementing or randomizing the value from iteration to iteration. However that wouldn’t make much sense because the values assigned by IANA for the application identifier are not incremental, decremental or follow any rule per say. TRex is a real traffic generator, and as such we need to provide an engine that takes in consideration the distribution of real traffic in order to generate application identifiers that would make sense. There are plenty of other data fields that need specific modification from iteration to iteration, hence we designed these engines to modify data per our needs.
Let us dive into it. Engines have 3 operations:
type FieldEngineIF interface { // Update updates the byte slice it receives with the new generated value. // It writes from the beginning of the slice. // If the length of the slice is shorter that the length of the variable we are // trying to write, it will return an error. // It is the responsibility of the caller to provide Update with a long enough // slice. It returns the number of bytes it wrote as the first integer parameter. Update(b []byte) (int, error) // GetOffset returns the offset of the packet as the interface was provided with. // The caller should use GetOffset to provide the interface with the correct // byte slice. GetOffset() uint16 // GetSize() returns the size of the variable that the engine will write in // the slice byte the next time it will be called. In order to provide a slice // long enough, the caller should use GetSize. GetSize() uint16 }
Engines are defined through simple JSON dictionaries. Let us look at the following example:
{ "engine_name": "interface", "engine_type": "uint", "params": { "size": 1, "offset": 1, "min": 1, "max": 24, "init": 5, "op": "inc", "step": 2 } }
-
sizerepresents the size of the variable that the engine will update. -
offsetrepresents the offset in the byte buffer that is provided in theUpdatecall.
When we call Update with some buffer on this engine, it will write 1 byte at offset 1. The first time we call Update the result will be 5 (init value) and then 7, 9 and so on, until we wrap around and continue again.
Possible sizes are {1, 2, 4, 8} meaning we can modify all of {uint8, uint16, uint32, uint64}.
Possible operations are {inc, dec, rand}. The step and init value can be anything on the domain range (max - min + 1).
|
|
The |
We can also generate floats using engines. For example:
{ "engine_name": "cool_floats", "engine_type": "float", "params": { "size": 4, "offset": 0, "min": -2.5, "max": 3.14, } }
In float engines, there are no increment or decrement notations. This is because such operations don’t make sense on real numbers.
Hence the only supported operation is random. For example, this engine will generate random float32 (4 bytes) values such that: min < = generate value < max.
Sometimes however, we want to generate values from a specific list of values. For this purpose we have have the following list engines.
{ "engine_type": "int_list", "engine_name": "int_list_dec", "params": { "size": 2, "offset": 4, "op": "dec", "list": [-5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5, 5, 5], "step": 2, "init_index": 4 } }
In this engine we can iterate the values of the provided list in incremental, decremental or random order. In the first two cases the step and the init_value can be any value between 0 and the list size.
For example with this engine, at bytes 4-5 of the provided buffer (offset=4, size=2) we will write 0xFF, 0xFF (-1 in 2’s complementary) (init_index=4) and then -3 in 2’s complementary, (op=dec and step=2), -5, 5 and so on.
The same can be done with strings or floats. For example we can write the following engine:
{ "engine_type": "string_list", "engine_name": "string_list_inc", "params": { "size": 20, "offset": 0, "op": "inc", "list": ["TRex", "Cisco", "AVC", "EMU", "Golang", "🤩"] } }
{ "engine_type": "float_list", "engine_name": "float_list_dec", "params": { "size": 8, "offset": 0, "op": "dec", "list": [3.14, 2.71, 1.62, 0.1, 1.44] "init_index": 4 } }
Pay attention that for list engines the default step=1 and the default init_index=0.
The engines we saw until here are very simple and do some simple operation. In case the operation is random it will pick a random value in the domain with uniform probability. But in order to simulate real life cases we need fast non uniform random distribution. Hence we have the following engines:
{ "engine_name": "minTTL", "engine_type": "histogram_uint", "params": { "size": 1, "offset": 0, "entries": [ { "v": 64, "prob": 1 }, { "v": 128, "prob": 2 }, { "v": 192, "prob": 5 } ] } }
This engine will write 1 byte at offset 0 of the provided buffer. It will write 64 with probability 1/8, 128 with probability 2/8 and 192 with probability 5/8.
Possible sizes for this engine type are {1, 2, 4}.
For size 8, please use engine_type = "histogram_uint64". We have to thank Golang’s support of generics for that.
Another type of engine would be generating values in different ranges where each range has some probability of being chosen.
{ "engine_name": "initiatorPackets", "engine_type": "histogram_uint64_range", "params": { "size": 8, "offset": 0, "entries": [ { "min": 0, "max": 4294967295, "prob": 1 }, { "min": 4294967296, "max": 8589934591, "prob": 3 } ] } }
This engine will generate an uint64 (size = 8) and write at offset 0 of the buffer a value in
[0-4294967295] with probability 1/4 and a value in [4294967296-8589934591] with probability 3/4. After one entry is picked with the given probability, the value inside that entries domain
is generated uniformly. For sizes {1, 2, 4} please use "engine_type": "histogram_uint_range".
Now, let us look at an engine that picks an entry from a list with some predefined distribution.
{ "engine_name": "protocolIdentifier", "engine_type": "histogram_uint_list", "params": { "size": 1, "offset": 0, "entries": [ { "list": [17, 6], "prob": 5 }, { "list": [1], "prob": 1 } ] } }
This engine for example can be used to modify the protocol identifier. The value 1 represents ICMP and is picked with probability 1/6. The values 17, 6 represent UDP and TCP respectively. The entry containing this value will be picked with probability 5/6 and then one between TCP and UDP will be picked uniformly.
Time related fields need special handling and as such we created special engines for them. Time engines always come in couples and need an Engine Manager (will be defined shorty) to work.
Both of the engines time_start, time_end must be always provided.
{ "engine_name": "flowStartSysUpTime", "engine_type": "time_start", "params": { "size": 4, "offset": 0, "time_end_engine_name": "flowEndSysUpTime", "ipg_min": 10000, "ipg_max": 20000, "time_offset": 200000 } }, { "engine_name": "flowEndSysUpTime", "engine_type": "time_end", "params": { "size": 4, "offset": 0, "time_start_engine_name": "flowStartSysUpTime", "duration_min": 5000, "duration_max": 10000, } }
The size of these engines can be 4 or 8 bytes.
The Inter Packet Gap (IPG) will be a random value between ipg_min and ipg_max. The duration of the flow will be a random value between
duration_min and duration_max. Lastly the time_offset can be used to provide an offset from the beginning of time. This makes time engines quite modular, as
the can be used for relative times (time_offset = upTime) or absolute times (times_offset = UnixTime).
All the values are in milliseconds.
To generate hosts realistically, we provide an engine for building URLs.
{ "engine_name": "nbar2HttpHost", "engine_type": "histogram_url", "params": { "size": 60, "offset": 0, "entries": [ { "schemes": ["https"], "hosts": ["google.com"], "random_queries": true, "prob": 5 }, { "schemes": ["ftp"], "hosts": ["downloads.cisco.com", "software.cisco.com"], "paths": ["ios-xe", "nx-os"], "queries": ["version=16", "version=7"], "prob": 2 }, { "schemes": ["http", "https"], "hosts": ["trex-tgn.cisco.com"], "paths": ["doc", "releases", "sdk"], "prob": 3 } ] } }
Let us for a moment ignore the histogram and consider what an URL is. An URL is a combination of a scheme + host + path + query. An URL must have a scheme and a host but not
necessarily contain the other fields. The scheme and the host will be uniformly picked from the schemes list and the hosts list respectively.
A path list can be provided if the user wants to. If a path list is provided, a path will be picked from the path list, which implicitly contains the empty path.
Queries can be provided in a list as raw queries (which implicitly contains the empty query), or can be generated randomly using the random_queries flag. The queries list and the random_queries
flag are mutually exclusive.
Finally, the histogram picks an entry with that entries' probability, and generates an URL from that entry.
|
|
The |
Another important histogram engine is the histogram string engine. Many IPFix fields work with strings, some are of fixed length (for example 32 bytes) and some have variable length. We created a generic engine that generates strings with a given probability and works both with fixed and variable length fields by padding if necessary. Thanks to Golang’s native support of Unicode strings, the engine will support any Unicode strings.
Let us look at a fixed length field string histogram:
{ "engine_name": "interfaceName", "engine_type": "histogram_string","params": { "size": 32,
"offset": 0, "should_pad": True,
"entries": [ { "str": "Te0/0/0", "prob": 4, "padding_value": 35,
}, { "str": "Hu0/1", "prob": 1, "padding_value": 36, }, { "str": "Gi0", "prob": 2, } ] } }
The type of the engine is histogram_string
| |
| The maximum byte size of the encoded string can be 32 bytes | |
| Specifies that the string should be always padded to the maximum size. This should be true for fixed length fields and false for variable length fields. | |
| Some ASCII padding value. In this case it is #. The default value is 0x00. |
In this engine, the generated value will be padded to 32 bytes using the padding_value. By using the default padding value we get exactly the required behavior for IPFix fixed length works.
Let us look at a variable length field string histogram:
{ "engine_name": "variableLength", "engine_type": "histogram_string","params": { "size": 10,
"offset": 2, "should_pad": False,
"entries": [ { "str": "Cisco", "prob": 1, "padding_value": 35,
}, { "str": "TRex", "prob": 2, }, { "str": "TRex-Emu", "prob": 1, } ] } }
The type of the engine is histogram_string too.
| |
| The maximum size of an allowed field. | |
| The string is not padded, it is encoded in its original length. Use this for variable length strings. | |
| Padding value can be given but it is ignored. |
We will summarize the engines and their types in the following table:
| Engine Type | Parameters | Histogram Entry | Type | Mandatory | Description |
|---|---|---|---|---|---|
(u)int |
size |
uint16 |
Yes |
Size of the (u)int in bytes. Possible values for (u)int are 1, 2, 4, 8. |
|
offset |
uint16 |
Yes |
Offset to write in the provided buffer. |
||
op |
string |
Yes |
Operation. Can be |
||
step |
uint64 |
No |
Step in case of inc, dec. Should be a value that can be expressed with |
||
min |
(u)int64 |
Yes |
Min value to be generated. Should be a value that can be expressed with |
||
max |
(u)int64 |
Yes |
Max value to be generated. Should be a value that can be expressed with |
||
init |
(u)int64 |
No |
Value between min and max from where we start the generation. Default = min. |
||
float |
size |
uint16 |
Yes |
Size of the float in bytes. Possible values for float are 4, 8 (float32, float64). |
|
offset |
uint16 |
Yes |
Offset to write in the provided buffer. |
||
min |
float64 |
Yes |
Min value to be generated. In case of size=4 it will be represented by float32. |
||
max |
float64 |
Yes |
Max value to be generated. In case of size=4 it will be represented by float32. |
||
(u)int_list / float_list / string_list |
size |
uint16 |
Yes |
Size of the (u)int/float/string in bytes. For (u)int/float lists, possible values are as aforementioned. Strings should have a value longer than any string in the |
|
offset |
uint16 |
Yes |
Offset to write in the provided buffer. |
||
op |
string |
Yes |
Operation. Can be |
||
step |
uint64 |
No |
Step in case of inc, dec. Should be between 0 and size of |
||
init_index |
uint64 |
No |
The index from where to start in the list. Should be between 0 and size of the |
||
list |
[](u)int64 / []float64 / []string |
Yes |
List of (unsigned) integers/floats/strings. Each value must be expressed with |
||
padding_value |
uint8 |
No |
Padding value for |
||
histogram_(u)int(64) |
size |
uint16 |
Yes |
Size of (u)int entry in bytes. If using |
|
offset |
uint16 |
Yes |
Offset to write in the provided buffer. |
||
entries |
[]dictionaries |
Yes |
List of dictionary where each dictionary represents an entry for the histogram. |
||
v |
(u)int32/64 |
Yes |
Value for this entry. Should be a value that can be expressed with |
||
prob |
uint32 |
Yes |
Probability for this entry to be picked. Any integer bigger than 0. The probabilities will be scaled automatically. |
||
histogram_(u)int(64)_range |
size |
uint16 |
Yes |
Size of (u)int entry in bytes. If using |
|
offset |
uint16 |
Yes |
Offset to write in the provided buffer. |
||
entries |
[] dictionaries |
Yes |
List of dictionary where each dictionary represents an entry for the histogram. |
||
min |
(u)int32/64 |
Yes |
Min value that can be generated by this entry. Should be a value that can be expressed with |
||
max |
(u)int32/64 |
Yes |
Max value that can be generated by this entry. Should be a value that can be expressed with |
||
prob |
uint32 |
Yes |
Probability for this entry to be picked. Any integer bigger than 0. The probabilities will be scaled automatically. |
||
histogram_(u)int(64)_list |
size |
uint16 |
Yes |
Size of (u)int entry in bytes. If using |
|
offset |
uint16 |
Yes |
Offset to write in the provided buffer. |
||
entries |
[]dictionaries |
Yes |
List of dictionary where each dictionary represents an entry for the histogram. |
||
list |
[](u)int32/64 |
Yes |
List of values for this entry. Every list value must be able to fit in |
||
prob |
uint32 |
Yes |
Probability for this entry to be picked. Any integer bigger than 0. The probabilities will be scaled automatically. |
||
time_start |
size |
uint16 |
Yes |
Size of the timestamp in bytes. Possible values are 4, 8. |
|
offset |
uint16 |
Yes |
Offset to write in the provided buffer. |
||
time_end_engine_name |
string |
Yes |
Exact name that will be given to the |
||
time_offset |
uint64 |
No |
The first packet offset from the starting point in milliseconds. Can be relative (uptime) or absolute (Unix time). Default = 0. |
||
ipg_min |
uint64 |
Yes |
Minimal Inter Packet Gap of this flow in milliseconds. |
||
ipg_max |
uint64 |
Yes |
Maximal Inter Packet Gap of this flow in milliseconds. The IPG will be a uniformly picked value between min and max duration. |
||
time_end |
size |
uint16 |
Yes |
Size of the timestamp in bytes. Possible values are 4, 8. Must be the same as in |
|
offset |
uint16 |
Yes |
Offset to write in the provided buffer. |
||
time_start_engine_name |
string |
Yes |
Exact name that will be given to the |
||
duration_min |
uint64 |
Yes |
Minimal duration for this flow in milliseconds. |
||
duration_max |
uint64 |
Yes |
Maximal duration for this flow in milliseconds. The duration will be a uniformly picked value between min and max duration. |
||
histogram_url |
size |
uint16 |
Yes |
Maximum size of url in bytes. Provide a large enough buffer to hold the longest url that can be generated. |
|
offset |
uint16 |
Yes |
Offset to write in the provided buffer. |
||
entries |
[]dictionaries |
Yes |
List of dictionary where each dictionary represents an entry for the histogram. |
||
schemes |
[]strings |
Yes |
List of schemes for the URL. |
||
hosts |
[]strings |
Yes |
List of hosts for the URL. |
||
paths |
[]strings |
No |
List of possible paths for the URL. The empty path is implicitly provided. |
||
queries |
[]strings |
No |
List of possible raw queries for the URL. The empty query is implicitly provided. |
||
random_queries |
bool |
No |
Should generate random queries? Default is False. Mutually exclusive with the |
||
prob |
uint32 |
Yes |
Probability for this entry to be picked. Any integer bigger than 0. The probabilities will be scaled automatically. |
||
histogram_string |
size |
uint16 |
Yes |
Maximum size of string in bytes. Provide a large enough value to hold the longest string encoded. |
|
offset |
uint16 |
Yes |
Offset to write in the provided buffer. |
||
should_pad |
bool |
Yes |
Pad the encoded string to the maximum size using some UTF-8 padding value. This should be true for fixed length fields (padding the value will always give a fixed length buffer) and false for variable length fields. |
||
entries |
[]dictionaries |
Yes |
List of dictionary where each dictionary represents an entry for the histogram. |
||
str |
string |
Yes |
String to generate. Each string’s encoded length should be less or equal the maximum size. |
||
prob |
uint32 |
Yes |
Probability for this entry to be picked. Any integer bigger than 0. The probabilities will be scaled automatically. |
||
padding_value |
uint8 |
No |
Some UTF-8 order value for a padding character. This will be used to pad the encoded string to maximum size in case padding is set. Defaults to 0. |
|
|
(u)int means that both uint and int types are supported. |
4.1.1. Engine Manager
Multiple engines can be defined in the same time using a list of dictionaries, where each dictionary represents one engine. The engine manager is a singleton that aggregates all the engines and can be used to call all of the engines one after the other. It has a map that maps the engines by their name to the actual engine object. It also provides aggregated error counters.
5. Simulator
Getting TRex-EMU to run in debug mode together with TRex can be cumbersome, especially when all one wants is to simulate some short profile and see that it works. Imagine we are writing a profile from scratch, and we have a syntax in error in it. We will discover this only when the profile is loaded, which happens after TRex starts and after TRex-EMU starts.
If you find yourself in one of the following cases, you might consider using the simulator:
-
You are implementing a new plugin and want to verify the transmitted packets.
-
You are writing a new profile from scratch and want to verify it works.
-
You don’t require an interactive default gateway, you just need to send packets.
The EMU simulator is a straightforward tool that can simulate EMU profiles as we know them for a given duration of time. Let’s take a look at it:
scripts$ emu-sim -h usage: sim.py [-h] [-f FILE] [-o OUTPUT] [-d DURATION] [-j JSON] [-v] optional arguments: -h, --help show this help message and exit -f FILE, --file FILE Emu profile to simulate. (default: emu/simple_emu.py) #-o OUTPUT, --output OUTPUT output file for Emu simulation. (default: emu_out.pcap) #
-d DURATION, --duration DURATION duration of simulation in seconds. (default: 10) #
-j JSON, --json JSON JSON file to capture traffic, RPC, counters etc. for debug purposes. (default: None) #
-v, --verbose run Emu in verbose mode #
| Emu profile to simulate. | |
| Pcap file with the packets generated. Packets are dumped in K12 format. | |
| Duration of simulation in seconds. It might be slightly longer than the requested value. | |
| A JSON file with debug information. | |
| Emu server will be run in verbose mode. |
The simulator starts TRex-EMU as a standalone server, without TRex core. This means:
-
The transmitted packets are recorded and then forwarded to some dummy sink veth. Meaning, the tx packets are black holed.
-
There is no rx channel, hence no packets will be received from a default gateway.
These constraints seem too substantial, but for a developer who implements a new plugin and wants to see the packets TRex-EMU is generating it is more than enough.
5.1. Example
Let us show an example of how to use the simulator. We are going to use a Netflow profile, since Netflow is a plugin that doesn’t require any rx.
Let us use the emu/simple_ipfix.py profile. However we are going to make a small change.
The Netflow plugin starts sending traffic only after the default gateway’s MAC address is resolved. Since there is no rx, it can never be resolved by ARP. This is why we are going to set a fixed MAC address for the default gateway.
c = EMUClientObj(mac = mac.V(), ipv4 = ipv4.V(), ipv6 = ipv6.V(), ipv4_dg = dg_4.V(), ipv4_force_dg = True, #ipv4_force_mac = "00:00:00:01:00:01", #
plugs = {'ipfix': self.get_init_json(host_port), 'arp': {'enable': True}, 'ipv6': {}})
| We indicate that we are forcing the MAC address of the default gateway to be a fixed value. | |
| The value of the forced MAC. |
Now let’s simulate the profile for 2 seconds.
scripts$ emu-sim -f emu/simple_ipfix.py -o out.pcap -d 2
Let us take a look into the generated PCAP file:
From this PCAP we can verify:
-
The traffic is simulated for almost 2 seconds.
-
The traffic is simulated as instructed in the profile.
-
The destination MAC address is the fixed MAC address we just set.
|
|
The simulated time will always be slightly longer than the requested duration. This is because the operation of loading the profile and setting the duration in TRex-EMU is not atomic and is done in two different commands. Hence the extra time is the time it takes the simulator to set the duration in TRex-EMU after it loads the profile. |
The simulator can especially help us debug. Let’s see what happens when we run it with the appropriate flag.
scripts$ emu-sim -f emu/simple_ipfix.py -d 1 --json debug.json
Since the debug file is long we will show here part of it:
The debug json file contains:
-
RPC requests and responses
-
Packets
-
Counters
6. FAQ
6.1. I want to add more protocols, how can I do it?
The framework is written in Golang. I would start with ICMP plugin as it is the simplest example.
6.2. Is it possible to sync ASTF/STL clients addresses with TRex-EMU?
I would like to create 1000 clients using TRex-EMU and use the same DHCP/DHCPv6 address with ASTF/STL profile.
For STL you can use the Field engine but it is limited with the scale of ip pool. We would create a indirect table that could be filled with the information from TRex-EMU.
For ASTF there is no support and the MAC, IPv4, IPv6 would be static.
6.3. Why did you write all the RFCs from scratch?
Wouldn’t it be easier to use a user space TCP/IP stack for example Linux or FreeBSD?
The answer is that for traffic generation, the separation between kernel and user space presents a big challenge to our main objectives:
-
Scale (e.g. high rate of client creation)
-
Cohesiveness between protocols.
For example DHCP and 802.1x are implemented in user space while ARP/IPv6 ND are implemented in the kernel. Another example, IGMP is a user space socket option. To control many IGMP clients, one needs to create many processes that open sockets to Linux namespaces and this is not scalable.
The is a big penalty in our decision. We need to write from scratch the protocols, but there are some advantages:
-
The scale is very high
-
There is no separation between kernel/user-space
-
Can manipulate the code for traffic generation purposes
-
It’s fun to write in Golang
6.4. Why Golang and not Python or C++?
First, Golang was an experiment. You can see from the code that this is the first time the developers write in Golang. However, it is hard now to go back to C++.
Why not Python?
Python has a few drawbacks for this project:
-
Speed: x50 slower than Golang
-
Dynamic language: hard to tag and control a large code base
Why not C++?
-
Speed was not a concern and TRex-core became slow to build.
-
We wanted a scalable and more modular design as the scale in TRex-EMU is more from a functionality point of view (more protocol support, development speed etc) and not PPS.
What is missing in Golang:
-
Generic, interface{} is not enough.
6.5. I need to write a tunnel plugin like PPPoE/GRE, can I do it?
You can, but we should support it in the framework first.
7. For Developers
As you already know the Emulation Server was written in Go. The reasons and the penalties of this choice are mentioned in the FAQ, but one of the most important reasons in which we want to focus here is the modularity.
One of the basic laws of software design is the Law of Simplicity: The ease of maintenance of any piece of software is proportional to the simplicity of its individual pieces.
We wanted a simple model, taking into consideration that each protocol is self contained and independent of other protocols. This is where Go packages come into play.
Every protocol is written as a separate package and each of these packages are provided fundamentals such as:
-
JSON-RPC connectivity directly to the Client
-
Timers
-
Counter functionality
-
Testing Simulation
-
Monitoring/Capture
In the rare case where these protocols, also known as plugins, need to communicate with each other they can use a provided Event Bus to pass messages.
All of this was mentioned on the Emulation Support section. This section is meant to be a more hands-on tutorial on how to write a package/plugin/protocol.
7.1. Tutorial: How to write a plugin/package
The best way to learn is through examples. We recently implemented a few of these plugins/packages and the ping package is the most basic one. We will use it as an example to take you through the details and the decisions. We will mostly focus on the fundamentals aforementioned
as they are common to all packages.
- Goal
-
Offer ping functionality both for IPv4 and IPv6.
As every good piece of software written, it all starts with the design. We want to offer the ping functionality for both IPv4/6 and as such let us understand the differences between the two. As it happens to be the only difference is the Type Code field, and we understand that a lot of code can be shared here.
Hence, we decide to write the ping functionality in a separate package with ICMPv4/ICMPv6 making use of this package as a black box.
7.1.1. JSON-RPC functionality
The JSON-RPC commands might be a bit different. For example, ICMPv4 uses a IPv4 destination address and ICMPv6 uses a IPv6 destination address. Each of these commands will then be in the respective package. We will show you for example the ping command RPC for both cases.
ApiIcmpClientStartPingHandler struct { // Amount of echo requests to send Amount uint32 `json:"amount" validate:"ne=0"` // Pace of sending the Echo-Requests in packets per second. Pace float32 `json:"pace" validate:"ne=0"` // The destination IPv4 Dst core.Ipv4Key `json:"dst"` // Timeout from last ping until the stats are deleted. Timeout uint8 `json:"timeout" validate:"ne=0"` // Payload size in bytes PayloadSize uint16 `json:"payloadSize" validate:"gte=16"` } /* ServeJSONRPC for ApiIcmpClientStartPingHandler starts a Ping instance. Returns True if it successfully started the ping, else False. */ func (h ApiIcmpClientStartPingHandler) ServeJSONRPC(ctx interface{}, params *fastjson.RawMessage) (interface{}, *jsonrpc.Error) { tctx := ctx.(*core.CThreadCtx) p := ApiIcmpClientStartPingHandler{Amount: ping.DefaultPingAmount, Pace: ping.DefaultPingPace, Dst: icmpClient.Client.DgIpv4, Timeout: ping.DefaultPingTimeout, PayloadSize: ping.DefaultPingPayloadSize} err1 := tctx.UnmarshalValidate(*params, &p) if err1 != nil { return nil, &jsonrpc.Error{ Code: jsonrpc.ErrorCodeInvalidRequest, Message: err1.Error(), } } // The ping logic. } // Register the command with its handler. core.RegisterCB("icmp_c_start_ping", ApiIcmpClientStartPingHandler{}, true)
Let’s cap what we need for an RPC command. We need to register the command name with a handler. This handler is a struct (a concrete type), whose fields are the JSON parameters.
This struct must have a method named ServeJSONRPC (to satisfy a Go interface) which Unmarshalls and Validates the JSON parameters into the struct we defined.
The IPv6 is almost the same but we will show it for the sake of being complete.
ApiIpv6StartPingHandler struct { // Amount of echo requests to send Amount uint32 `json:"amount" validate:"ne=0"` // Pace of sending the Echo-Requests in packets per second. Pace float32 `json:"pace" validate:"ne=0"` // The destination IPv6 Dst core.Ipv6Key `json:"dst"` // The source IPv6 Src core.Ipv6Key `json:"src"` // Timeout from last ping until the stats are deleted. Timeout uint8 `json:"timeout" validate:"ne=0"` // Payload size bytes PayloadSize uint16 `json:"payloadSize" validate:"gte=16"` } /* ServeJSONRPC for ApiIpv6StartPingHandler starts a Ping instance. Returns True if it successfully started the ping, else False. */ func (h ApiIpv6StartPingHandler) ServeJSONRPC(ctx interface{}, params *fastjson.RawMessage) (interface{}, *jsonrpc.Error) { tctx := ctx.(*core.CThreadCtx) c, err := getClient(ctx, params) if err != nil { return nil, err } dgIpv6, dgOk := c.Client.ResolveDGIPv6() p := ApiIpv6StartPingHandler{Amount: ping.DefaultPingAmount, Pace: ping.DefaultPingPace, Dst: dgIpv6, Src: c.Client.ResolveSourceIPv6(), Timeout: ping.DefaultPingTimeout, PayloadSize: ping.DefaultPingPayloadSize} err1 := tctx.UnmarshalValidate(*params, &p) if err1 != nil { return nil, &jsonrpc.Error{ Code: jsonrpc.ErrorCodeInvalidRequest, Message: err1.Error(), } } // ping logic } // Register the command with its handler. core.RegisterCB("ipv6_start_ping", ApiIpv6StartPingHandler{}, true) // start ping
7.1.2. Declaring a new package
Now let us get into the ping package. Each package is defined in a new directory and every Go file in this directory contains the following package declaration:
// Package ping offer Echo Request-Response functionality for both ICMPv4/ICMPv6. // Also it partially supports other type of possible responses such as Destination Unreachable. package ping
Both of the ICMPv4/v6 import this package.
7.1.3. Timers
We mentioned that each plugin can use build in provided timers. We will get more into the details of that later but for now let us see the time objects. There are 2 main objects:
type Ping struct { timer core.CHTimerObj // timer object timerw *core.TimerCtx // timer wheel // Other fields are omitted for brevity }
A timer wheel is an object of type TimerCtx, a timer context which is shared between many plugins.
A timer object is an object which is used to hold the concrete type as a callback and call its OnEvent function when needed.
For example, the following lines are taken from ping:
// NewPing creates a new Ping instance and returns a pointer to it. func NewPing(params PingParams, ns *core.CNSCtx, pingClient PingClientIF) *Ping { o := new(Ping) // Omitted lines for brevity o.timer.SetCB(o, 0, 0) // set the callback to this object o.timerw = o.tctx.GetTimerCtx() // get the timer wheel //dTime is the delta time between two calls. dTime := time.Duration(float32(time.Second) / params.Pace) o.ticksPerInterval, o.pktsPerInterval = o.timerw.DurationToTicksBurst(dTime) o.timerw.StartTicks(&o.timer, o.ticksPerInterval) }
We saw that the client provided a field named Pace in the ping command that specifies how many packets per second (pps) to send.
Suppose Pace=2, we want to send 2 packets each second. So the code that sends packets must be called every dTime=0.5s.
However the timer works with ticks and not with duration.Time, and as such we convert the time to ticks using the DurationToTicksBurst function.
Lastly we instruct the timer to start ticking. After 0.5 seconds have passed the timer will call the OnEvent function of the callback concrete type we set using SetCB,
which looks like this:
/* OnEvent - Event Driven call. Possible Events: - Time to send another Echo Request - Stop waiting for an Echo Response, after sending all Echo Requests. */ func (o *Ping) OnEvent(a, b interface{}) { if o.sentRequests < o.params.Amount { o.sendPing() if o.sentRequests == o.params.Amount { timeout := time.Duration(o.params.Timeout) * time.Second ticks := o.timerw.DurationToTicks(timeout) o.timerw.StartTicks(&o.timer, ticks) } else { o.timerw.StartTicks(&o.timer, o.ticksPerInterval) } } else { // Should have collected the records by now, timeout expired. o.OnRemove() } }
The OnEvent is called every 0.5 seconds except for when we finished sending all the pings. In this case we start a timer for Timeout seconds to allow the user to collect the ping statistics.
Pay attention to the following two functions we used to calculate ticks:
-
DurationToTicksBurst -
DurationToTicks
These two functions both calculate ticks given a time.Duration object but they are different. The timer works with a minimal resolution which can be calculated using the following function:
//MinTickMsec() return how long take a one tick in msec by default it is 10 func (o *TimerCtx) MinTickMsec() uint32 { return uint32(o.TickDuration / time.Millisecond) }
If your time.Duration is smaller than this minimal resolution please use the former to send bursts of packets and work at minimal resolution. Else, use the later.
|
|
We see here a pure Event Driven architecture. This is fundamental in a scale project such as TRex. Only this way we can achieve the extreme TX rates. If we only attempt a blocking approach we wouldn’t even get close to these rates. |
7.1.4. Counters
A lot of protocols have counters and statistics and our ping package is no different. We offer build in functionality for counters as well, hence no need to reinvent the wheel.
The first step is to define these counters in a new struct.
// PingStats contains the data that will be returned to the client. // This should be unique per each Ping Identifier. type PingStats struct { requestsSent uint32 // how many Echo Requests were sent requestsLeft uint32 // how many Echo Requests are left to send repliesBadIdentifier uint32 // how many Echo Replies with bad identifier received repliesMalformedPkt uint32 // how many malformed Echo replies were received repliesBadLatency uint32 // how many Echo Replies with bad latency were received dstUnreachable uint32 // how many Destination Unreachable were received repliesInOrder uint32 // how many Echo Replies received in order repliesOutOfOrder uint32 // how many Echo Replies received out of order avgLatency time.Duration // the average latency avgLatencyUsec int64 // the average latency in usec minLatency time.Duration // the minimal latency minLatencyUsec int64 // the minimal latency in usec maxLatency time.Duration // the maximal latency maxLatencyUsec int64 // the maximal latency in usec }
Note that not all of these counters need to be returned to the client, some might be for internal use.
Those counters we want to return to the user we add in a database, by creating a CCounterDb in the following way:
//Creates a database of ping stats func NewPingStatsDb(o *PingStats) *core.CCounterDb { db := core.NewCCounterDb("icmp_ping_stats") db.Add(&core.CCounterRec{ Counter: &o.requestsSent, Name: "requestsSent", Help: "tx echo requests sent", Unit: "pkts", DumpZero: false, Info: core.ScINFO}) // Lines omitted for brevity return db }
The ping struct we saw before has two more fields for the counters which are initialized hte following way
type Ping struct { cdb *core.CCounterDb // Counter Database for Stats cdbv *core.CCounterDbVec // Database Vector // Other fields are omitted for brevity } // NewPing creates a new Ping instance and returns a pointer to it. func NewPing(params PingParams, ns *core.CNSCtx, pingClient PingClientIF) *Ping { o := new(Ping) o.stats = new(PingStats) o.cdb = NewPingStatsDb(o.stats) o.cdbv = core.NewCCounterDbVec("icmp_ping_stats") o.cdbv.Add(o.cdb) // NOTE: Lines omitted for brevity }
The counter database would have sufficed in our case. However, a big part of the functionality is offered by the database vector, hence we hold a database vector of only one entry. We can at anytime return a JSON version of the stats:
// GetPingCounters returns the Ping counters. // The params decides things like the verbosity, filtering or whether to dump zero errors. // The counters are updated before returning them. func (o *Ping) GetPingCounters(params *fastjson.RawMessage) (interface{}, *jsonrpc.Error) { var p core.ApiCntParams o.updateStats() return o.cdbv.GeneralCounters(nil, o.tctx, params, &p) }
Using the params field we can decide the granularity of the information we return, such as units, filtering, verbosity etc.
7.1.5. Testing simulation
Another basic law of software design is the Law of Testing which says: The degree to which you know how your software behaves is the degree to
which you have accurately tested it.
First and foremost, our package needs to know if it is being tested or not. For example, in order to measure latency, we encode a timestamp of nanosecond resolution when sending the packet in the payload. We simply can’t test our latency calculation’s correctness unless we know we are in a test simulation environment and use a fixed value in this case. Hence, our package can do something like this:
if !o.tctx.Simulation { o.identifier = uint16(rand.Intn(0xffff)) o.sequenceNumber = uint16(rand.Intn(0xffff)) } else { o.identifier = 0x1234 o.sequenceNumber = 0xabcd timestamp = 128 }
Writing tests in Golang is really easy. We won’t get in all of the details but we will mention the basics.
First, we can use timers in tests just like we used them in the real package, with callbacks and flags to capture and compare.
func TestPluginIcmp3(t *testing.T) { a := &IcmpTestBase{ testname: "icmp3", monitor: true, match: 2, capture: true, duration: 3 * time.Minute, clientsToSim: 1, amount: 5, cb: rpcQueue, } a.Run(t, true) }
Secondly, we can simulate JSON-RPC requests in the following way:
o.tctx.Veth.AppendSimuationRPC([]byte(`{"jsonrpc": "2.0", "method":"icmp_c_start_ping", "params": {"tun": {"vport":1,"tci":[1,2]}, "mac": [0, 0, 1, 0, 0, 0], "amount": 5, "pace": 1, "dst": [16, 0, 0, 1], "payloadSize": 20}, "id": 3}`))
|
|
For this to work, we clearly need to simulate the clients and namespaces with the appropriate parameters as well. |
The idea behind this test is to create a golden file, with a packet dump (k12 format) and counters. Afterwards, each time we run the test we compare the generated output to the golden file.
$:src$ go test -v emu/plugins/icmp -run 3 === RUN TestPluginIcmp3 counters icmp db pktTxIcmpQuery : 5 pktRxIcmpResponse : 5 === --- PASS: TestPluginIcmp3 (0.01s) PASS ok emu/plugins/icmp 0.024s
The generated file can be found unit-test/generated and the expected file is found in unit-test/expected.
Lastly, we can monitor and see the capture:
$:src$ go test -v emu/plugins/icmp -run 3 --monitor 1 > /tmp/a.pcap
7.2. Transport layer
7.2.1. Intro
EMU started as a framework to implement L2/L3 protocols but as soon as we understood its potential we implemented even L7 protocols, like Netflow for example. However, L7 protocols need the transport layer. In case of UDP, it is simple really. But in case of TCP it gets complex. We can’t expect each L7 protocol to implement its own TCP or UDP layer. Hence we introduce sockets.
Sockets can be used by plugins just like sockets of the OS. The Client Transport Context (CTX) will be loaded dynamically only when the first socket is used. It is designed that way in order to save memory in case there is no use of TCP/UDP, for example, in case of DOT1X, ICMP, etc..
The TCP logic was imported from BSD C code to native Golang (from TRex-Core).
The sockets work in an event driven architecture. This is similar to NodeJS and not Golang which uses micro-threads.
7.2.2. Tutorial: Sockets, how to?
Let us see the basic example of how to work with sockets. First step, let us create a couple of sockets:
package socketApp import ( "emu/core" "emu/plugins/transport" ) type SocketApp struct { ctx *transport.TransportCtx // client transport context ipv4 transport.SocketApi // some IPv4 socket ipv6 transport.SocketApi // some IPv6 socket } func (o *SocketApp) CreateSockets(client *core.CClient) error { o.ctx = transport.GetTransportCtx(client) //var err error o.ipv4, err = o.ctx.Dial("udp", "48.0.0.1:80", o, nil, nil, 0) //
if err != nil { return err } o.ipv6, err = o.ctx.Dial("tcp", "[2001:db8::3000:1]:80", o, nil, nil, 65001) //
if err != nil { return err } return nil }
| Get the client transport context. | |
| Create an HTTP/UDP/IPv4 socket. | |
| Create an HTTP/TCP/IPv6 socket with source port 65001. |
While the first two arguments of Dial are self explanatory, let us discuss the other ones:
-
The third argument is a callback object. A socket is an interface, and in case of events in needs a callback. So in our
SocketAppwe need to implement the following three functions which will be called by the socket in case of an event.
func (o *SocketApp) OnRxEvent(event transport.SocketEventType) { } func (o *SocketApp) OnRxData(d []byte) { } func (o *SocketApp) OnTxEvent(event transport.SocketEventType) { }
-
The fourth argument is an
IoctlMapfor TCP flags. See how for example we can set TTL to 255.
var ioctlMap transport.IoctlMap = make(map[string]interface{}) // According to RFC 3171 a packet sent to the Local Network Control Block (224.0.0.0/24) // should be sent with TTL=255 ioctlMap["ttl"] = 255 o.ipv4, err = transportCtx.Dial("udp", Ipv4Address, o, ioctlMap, nil, 0)
-
The fifth argument is a pointer to MacAddress. In case it is not
nil, this will be the destination MacAddress. It is especially useful for multicast or broadcast. For example, in the mDns protocol we can see:
/* RFC 6762 A compliant Multicast DNS querier, which implements the rules specified in this document, MUST send its Multicast DNS queries from UDP source port 5353 (the well-known port assigned to mDNS), and MUST listen for Multicast DNS replies sent to UDP destination port 5353 at the mDNS link-local multicast address (224.0.0.251 and/or its IPv6 equivalent FF02::FB). */ o.ipv4, err = transportCtx.Dial("udp", Ipv4Address, o, ioctlMap, &Ipv4McastMacAddress, 5353)
-
The last argument specifies the source port. If provided and not zero, the socket will not allocate a source port but use the one provided. Use this with great care, as there is no mechanism that indentifies already used ports. The previous example shows one possible use.
The socket API is quite simple:
type SocketApi interface { Close() SocketErr // close the connection **after** all the tx queue was flushed Shutdown() SocketErr // shutdown connection immediately LocalAddr() net.Addr RemoteAddr() net.Addr GetCap() SocketCapType // get the capability of the socket e.g. SocketCapStream GetLastError() SocketErr SetIoctl(m IoctlMap) error // set ioctl options to the socket e.g. {"no_delay":0} GetIoctl(m IoctlMap) error // get the value for each key Write(buf []byte) (err SocketErr, queued bool) GetL7MTU() uint16 // Returns the L7 MTU. IsIPv6() bool // Returns True if the IP layer is IPv6, False if it is IPv4. GetSocket() interface{} // return internal raw socket *TcpSocket for testing }
The next step in our tutorial is to implement a simple function in our SocketApp that writes in the socket. The socket API offers a Write function which we can call.
But unfortunately it is not that simple. Before calling Write on the socket we must make sure that the destination MAC address is resolved. This isn’t trivial since the ARP request might take some time.
In case the MAC address is not resolved, the writing will fail.
Fortunately, we will get an event in case of resolve. Let’s review our SocketApp. We should edit our struct to contain two new flags:
type SocketApp struct { ctx *transport.TransportCtx // client transport context ipv4 transport.SocketApi // some IPv4 socket ipv6 transport.SocketApi // some IPv6 socket dg4Resolved bool // DG for IPv4 resolved dg6Resolved bool // DG for IPv6 resolved }
Upon creation of our app we will register for an event in case of resolve:
func CreateSocketApp(ctx *core.PluginCtx) *SocketApp { o := new(SocketApp) o.InitPluginBase(ctx, o) // Init base object var socketAppEvents = []string{core.MSG_DG_MAC_RESOLVED} o.RegisterEvents(ctx, socketAppEvents, o) // Register events, only if they exist } func (o *SocketApp) OnEvent(msg string, a, b interface{}) { switch msg { case core.MSG_DG_MAC_RESOLVED: bitMask, ok := a.(uint8) if !ok { // failed at type assertion return } resolvedIPv4 := (bitMask & core.RESOLVED_IPV4_DG_MAC) == core.RESOLVED_IPV4_DG_MAC resolvedIPv6 := (bitMask & core.RESOLVED_IPV6_DG_MAC) == core.RESOLVED_IPV6_DG_MAC if !o.dg4Resolved && resolvedIPv4 { o.dg4Resolved = true } if !o.dg6Resolved && resolvedIPv6 { o.dg6Resolved = true } } }
Now we can implement our simple Write function:
func (o *SocketApp) Write(msg []byte) (err4, err6 transport.SocketErr) { if o.dg4Resolved { err4, _ = o.ipv4.Write(msg) } if o.dg6Resolved { err6, _ = o.ipv6.Write(msg) } return err4, err6 }
For a more detailed and complete example, we ask you to explore the transport_example plugin.
7.2.3. Transport Counters
The TCP/UDP counters can be inspected using the console:
emu>emu_transport_show_counters -p 0 --mac 00:00:00:70:00:02 Ft Counters name | value ------------------+------ dial | 1 src_port_alloc | 1 src_port_free | 1 ft_addv4 | 1 ft_removev4 | 1 ft_lookupv4 | 10626 ft_lookup_foundv4 | 10626 Tcp Counters name | value ----------------+--------- already_closed* | 1 connattempt | 1 connects | 1 segstimed | 739 rttupdated | 3628 delack | 1 sndtotal | 10784 sndpack | 7000 predack* | 659 rcvackbyte_of | 1 sndrexmitpack* | 7 sndrexmitbyte* | 10136 rcvoopackdrop* | 1 rexmttimeo* | 7 preddat | 6998 rcvackbyte | 10000000 rcvackpack | 3627 rcvbyte | 10000000 rcvpack | 7000 sndacks | 3775 sndctrl | 2 sndbyte_ok | 10000000 29.96 [ms]
7.3. Proxy
7.3.1. Intro
Take a look again at the TRex architecture as shown in [Architecture]. The EMU communicates with the TRex core through a ZMQ tunnel which can run on top of IPC or TCP. The packets that the EMU generates are sent to the RX core of the TRex server through this ZMQ tunnel, and from there to the NIC. This architecture makes sense in production. When talking scale, we indeed need this fast but long path.
However, when developing, we need to check correctness and not only scale. To check correctness, the previous architecture proves to be burdensome. Take for example the ICMP plugin we discussed in depth in this document. To verify it works, we pinged a router. Can’t we ping the machine in which the EMU runs and expect it to ping us back?
Hence we introduce the Proxy. The Proxy is a small proxy build in Golang, which can run in any Linux distribution. The Proxy installs a TAP in the machine it runs. It then opens two ZMQ channels with the EMU, just like the RX of the TRex core.
The architecture looks like this:
|
|
The Proxy runs on the same machine as the Kernel. The EMU doesn’t necessarily. |
7.3.2. Tutorial: Ping
In this simple tutorial we will show you how you can ping with ease using this architecture. We will create a TAP interface whose IPv4 configuration will be 11.0.0.1/24.
Then we will use the EMU to emulate a client with IPv4 of 11.0.0.2 and default gateway of 11.0.0.1. Then we will ping the Kernel from the EMU.
First we create the TAP:
scripts$ sudo ./mktapWe can verify that the TAP is created:
scripts$ ifconfig tap0 tap0 Link encap:Ethernet HWaddr 8a:48:87:ed:00:0b inet addr:11.0.0.1 Bcast:0.0.0.0 Mask:255.255.255.0 UP BROADCAST MULTICAST MTU:1500 Metric:1 RX packets:0 errors:0 dropped:0 overruns:0 frame:0 TX packets:0 errors:0 dropped:0 overruns:0 carrier:0 collisions:0 txqueuelen:500 RX bytes:0 (0.0 B) TX bytes:0 (0.0 B)
|
|
The mktap script adds a iptable ACCEPT rule. This is necessary in our setups which have firewall rules, otherwise the Kernel will drop the incoming packets. The rule is deleted in the rmtap script. |
On the same terminal window, we can run the Proxy. If this is the first time you are running it, make sure the proxy is compiled:
src$ go install cmd-proxy/trex-emu-proxy.goscripts$ sudo ./proxyNext we run the EMU. I will be running it in the same machine and with IPC hence the flag -S will have a localhost address. As aforementioned, you can run it any machine and specify the address with -S, but if you work
remote remember to use TCP instead of IPC. Same here, if this is the first time you are running it, make sure the EMU is compiled:
src$ go install cmd/trex-emu.goscripts$ sudo ./trex-emu -S 127.0.0.1
|
|
The trex-emu file is found in the scripts folder of TRex-Core. We need sudo only because we are using IPC. If we use TCP instead we can run the Golang executable file from the EMU repo directly without root
permissions. |
Now let us connect a TRex console to the EMU server.
scripts$ ./trex-console --emu-only-serverThe --emu-only-server tells the console not to look for a running TRex Core instance. If we specify it without parameters, it will look for the EMU server in localhost, but we can specify any address, for
example --emu-only-server 192.168.1.1. Since I am running everything in the same machine, specifying the flag is enough.
|
|
The console is found in the scripts folder of the TRex-Core repo. |
Next, we load from the console a simple EMU profile which will create a client with IPv4 11.0.0.2 and default gateway 11.0.0.1 (TAP).
emu>emu_load_profile -f emu/simple_icmp_local.py -t --clients 1
We can verify this by:
emu>emu_show_all Namespace #1 Information Port | Vlan tags | Tpids | Plugins | #Clients -----+-----------+-------+------------------------------------+--------- 0 | - | - | arp, icmp, ipv6, transe, transport | 1 Clients Information MAC | IPv4 | DG-IPv4 | MTU | Plugins ------------------+----------+----------+------+----------------------------------- 00:00:00:70:00:02 | 11.0.0.2 | 11.0.0.1 | 1500 | arp, icmp, ipv6, transe, transport 26.25 [ms]
Now let us ping the default gateway (Kernel TAP):
emu>emu_icmp_ping -p 0 --mac 00:00:00:70:00:02 Starting to ping : [SUCCESS] Progress: 100.00%, Sent: 5/5, Rcv: 5/5, Err: 0/5, RTT min/avg/max = 0.72/1.29/3.43 ms Completed
And finally, after stopping the Proxy, we can remove the TAP interface:
scripts$ sudo ./rmtap7.3.3. Tutorial: TCP echo server
ICMP is a simple example to make sure everything works, but the purpose of the Proxy is to offer us as developers the correctness of the Kernel and its networking protocols. Anyone can implement a Echo Response server, but implementing the TCP stack is another story. The Proxy can be used to verify any protocol. Take for example Netflow. EMU implements the Netflow client side, but we need to test with a real collector. We can install an open source Netflow collector on top of the Linux Kernel and verify the correctness of EMU implementation.
Here we will show the idea with a simpler example. We will run a basic TCP echo server on the proxy machine and emulate TCP traffic with one of the EMU clients.
|
|
This time we will use ZMQ over TCP instead of ZMQ over IPC for the sake of completeness. |
First, let’s make the tap:
scripts$ sudo ./mktapThen we run the Proxy with TCP over ZMQ:
scripts$ sudo ./proxy --emu-zmq-tcpThen, we run the EMU with TCP over ZMQ. Pay attention that we can run this from the EMU repository and there is no need for root permissions.
src$ ../bin/trex-emu --emu-zmq-tcp -S 127.0.0.1
Next, let’s take a look at the simple TCP echo server:
package main import ( "bufio" "fmt" "net" "os" ) var port = "0.0.0.0:9001" func echo(conn net.Conn) { r := bufio.NewReader(conn) for { line, err := r.ReadBytes(byte('\n')) if err == nil { conn.Write(line) } else { break } } conn.Close() } func main() { l, err := net.Listen("tcp", port) if err != nil { fmt.Println("ERROR", err) os.Exit(1) } for { conn, err := l.Accept() if err != nil { fmt.Println("ERROR", err) continue } go echo(conn) } }
The server listens at port 9001 and simply echoes back whatever it receives.
Let’s compile the server:
src$ go install cmd-test/tcp-server/tcp_server.goNow, let’s run it:
src$ ../bin/tcp_serverNext, we will connect the console to the EMU server and emulate one client which sends TCP traffic at port 9001.
scripts$ ./trex-console --emu-only-serverLet’s add one client which makes use of the transe plugin. This plugin is a simple plugin which sends TCP traffic. The name derives from tranport example.
We can see the relevant configuration from the simple_icmp_local.py profile here:
self.def_c_plugs = { 'arp': {}, 'icmp': {}, 'ipv6': {}, 'transport': {}, 'transe': {'addr':'11.0.0.1:9001', 'size':100000, 'loops':100} }
emu>emu_load_profile -f emu/simple_icmp_local.py -t --clients 1
We can see the counters:
emu>emu_transe_show_counters -p 0 Transe Counters name | value ------------+--------- pktClient | 1 rxByteTotal | 10000000 txByteTotal | 10000000 pktRxEvent | 7000 pktTxEvent | 100 5.38 [ms]
From the client’s counters we see that the TCP server running on top of the Linux Kernels, echoes back. We can see this even better if we run the EMU in monitor mode, but we will leave this as an exercise for the reader.
8. Network Topologies
Different protocols require different network topologies to test. EMU supports protocols in all layers.
-
L2 multicast protocols (CDP, LLDP, mDNS)
-
Protocols between L2-L3 such as ARP
-
L3 protocols such as IPv6
-
L4 is provided by ICMP and the transport plugin (TCP/UDP)
-
L7 protocols such as Netflow, TDL
Clearly, the network topology you need for mDNS is not the same as the network topology you need for Netflow. This section’s purpose is to provide common examples of network topologies.
8.1. L2 communication
Multiple protocols communicate in L2. This includes L2 unicast communication but also L2 multicast communication such as mDNS, CDP, LLDP.
Let’s recap how EMU clients work. Each client belongs to some namespace, which can be uniquely identified by a tuple of (Tpid, Tci, Port). Pay attention to the following limitation.
|
|
Clients behind the same physical port can’t communicate at L2. |
A very common L2 communication case is that clients in the same namespace communicate one with the other. Unfortunately this is not supported at the moment. For L2 communication, two clients must sit behind different physical ports.
There are two common setups for L2 communication:
8.1.1. Loopback
A loopback connection looks like this:
In this case, everything transmitted from port 0 will get to port 1 and vice-versa. For L2 communication, we set the TRex port addresses in the same subnet. For example, if we assume CIDR /24, we can use the following trex_cfg.yaml:
- port_limit: 2 version: 2 interfaces: ['87:00.0', '87:00.1'] port_info: - ip: 1.1.1.1 default_gw: 1.1.1.128 - ip: 1.1.1.128 default_gw: 1.1.1.1
At EMU level, we can create a namespace at each port and attach clients. One such example, can be the following profile:
trex(service-filtered)>emu_show_all Namespace 1 Information Port | Vlan tags | Tpids | Plugins | Clients -----+-----------+-------+-----------------------+--------- 0 | - | - | arp, icmp, ipv6, mdns | 2 Clients Information MAC | IPv4 | DG-IPv4 | MTU | Plugins ------------------+---------+----------+------+---------------------- 00:00:00:70:00:03 | 1.1.1.3 | 1.1.1.16 | 1500 | arp, icmp, ipv6, mdns 00:00:00:70:00:04 | 1.1.1.4 | 1.1.1.16 | 1500 | arp, icmp, ipv6, mdns Press Enter to see more namespaces Namespace 2 Information Port | Vlan tags | Tpids | Plugins | Clients -----+-----------+-------+-----------------------+--------- 1 | - | - | arp, icmp, ipv6, mdns | 2 Clients Information MAC | IPv4 | DG-IPv4 | MTU | Plugins ------------------+---------+---------+------+---------------------- 00:00:00:70:00:05 | 1.1.1.5 | 1.1.1.1 | 1500 | arp, icmp, ipv6, mdns 00:00:00:70:00:06 | 1.1.1.6 | 1.1.1.1 | 1500 | arp, icmp, ipv6, mdns 1.80 [sec]
Note that clients in the same namespace won’t be able to communicate, however clients in different namespaces can communicate at L2 without any problem.
8.1.2. L2 switch
A setup using a L2 switch looks like this:
Even in this case, two clients sitting behind the same physical port can’t communicate because:
|
|
If the port on which the frame is received is the same port where the target destination resides, the switch can simply discard the frame because it can be assumed that the target will have received the frame through the normal LAN delivery mechanisms. |
That also means, that two clients in the same namespace won’t be able to communicate.
8.2. L3 communication
Most of the protocols require L3 communication. An L3 setup can use two different ports of a router, or one single port with multiple sub-interfaces. In this type of communication, the EMU client will always use the default gateway’s MAC address as the destination MAC address. The default gateway’s MAC address can be learnt using ARP or Router Advertisement.
|
|
Two EMU clients in the same namespace can communicate at L3 through the default gateway. |
One such example can be found in the ICMPv4 tutorial.
Table of Contents