Ansible Automation on Ubuntu 20.04 in GNS3

Ansible is a useful tool for automating tasks on various systems, including servers and network devices. It can be a little tricky to set up, but it’s ok once you get the hang of it. Today we’ll just try to get ansible installed on an Ubuntu 20.04 server and able to connect to another Ubuntu server, a Rocky Linux server, and a Cisco IOSv router.

Topology

Ansible in GNS3

Our simple subnet of 172.16.0.0/24 will hold a Ubuntu 20.04 server at the top at 172.16.0.1 acting as the ansible controller. The others will all be managed nodes, they don’t have ansible installed. Ansible uses python3 on Linux servers to execute various commands, and it’s not installed by default on Rocky Linux 8.5, so I installed it. I also added a firewall to the Rocky node to allow SSH in, which is how ansible connects to nodes. The SSH server has been enabled on the Cisco IOSv router as well.

Installation

Following ansible’s official installation instructions, this quick script will get it installed. Comments are inline:

#Create apt file for ansible
touch /etc/apt/sources.list.d/ansible.list

#Add ppa to above file
echo '
deb http://ppa.launchpad.net/ansible/ansible/ubuntu focal main
' >> /etc/apt/sources.list.d/ansible.list

#Add key for ppa
apt-key adv --keyserver keyserver.ubuntu.com --recv-keys 93C4A3FD7BB9C367

#Update and install
apt-get update
apt-get install ansible

Ansible should now be installed!

Create inventory

The next thing to do is create an inventory file. Ansible keeps it’s config files in /etc/ansible, so we’ll start by writing a config to /etc/ansible/hosts. This file supports multiple formats, we’ll use yaml because I like yaml (don’t judge me!). This simple script (it’s just an echo command and redirect) will set up the hosts file:

echo '

servers:
  hosts:
    ubuntu:
      ansible_host: 172.16.0.2
    rocky:
      ansible_host: 172.16.0.3
  vars:
    ansible_python_interpreter: /usr/bin/python3  #specify python3 for ubuntu and rocky


routers:
  hosts:
    cisco:
      ansible_host: 172.16.0.4
      ansible_network_os: cisco.ios.ios                     #OS is Cisco IOS!
      ansible_connection: ansible.netcommon.network_cli     #connect to IOS via CLI, no python
      ssh_args: -oKexAlgorithms=+diffie-hellman-group1-sha1 #key exchange algorithm to support older IOS

' > /etc/ansible/hosts

Verify inventory connections

The below command will check the integrity of your inventory (hosts) file:

ansible-inventory --list -y

Then once you have worked out any inventory file issues, “ping” your hosts. This is not an ICMP echo-request/echo-reply (commonly known as ping), ansible will actually try to log in to each host via SSH. Ansible assumes you have SSH public/private key pair authentication enabled, but since this is in a test environment in GNS3 we’ll just pass the user and password to ansible on the command line:

ansible all -m ping --extra-vars "ansible_user=james ansible_password=james"
---

ubuntu | SUCCESS => {
    "changed": false,
    "ping": "pong"
}
rocky | SUCCESS => {
    "changed": false,
    "ping": "pong"
}
cisco | SUCCESS => {
    "changed": false,
    "ping": "pong"
}

With this, we’ve verified that we have configured our hosts and can properly connect to them from the controller.

Next we’ll try to make some changes with playbooks! Hope you liked this one.

Nagios Core – NCPA Agent on Ubuntu and Rocky Linux

Last time, we installed Nagios Core on Ubuntu Server 20.04. We saw how to add hosts and do a ping check to monitor network connectivity. Today we’ll learn how to check CPU, memory and processes. Nagios provides a free agent to do this that we can install on most standard Linux distributions (Ubuntu, Redhat, Debian, Amazon, etc) as well as Windows and MacOS.

This agent can monitor various services on its host machine, has a REST API and a nice web interface. It replaces the NRPE agent that came before it.

Topology

Topology in GNS3

Same as the previous post, our Ubuntu server at 172.16.0.1/24 will monitor the other two hosts, Rocky Linux and Cisco IOSv. We’ll be installing the NCPA agent on Rocky Linux 8.5 at 172.16.0.2.

Installation

On Rocky Linux 8.5, installation is pretty quick using the official Nagios repository. We’ll add the repository and install the package:

rpm -Uvh https://repo.nagios.com/nagios/8/nagios-repo-8-1.el8.noarch.rpm
yum install ncpa -y

Then we need to allow incoming connections through the firewall on tcp port 5693, which is the default port that NCPA uses:

firewall-cmd --zone=public --add-port=5693/tcp --permanent
firewall-cmd --reload

If everything is installed correctly, you should be able to reach the NCPA web interface using the Rocky Linux server’s IP address. Make you use https and port 5693 –> https://<ip address or fqdn>:5693. The default password is “mytoken” which you’ll want to change via the configuration file before putting this in production. But for now it should look like this:

NCPA Web Interface

Nagios Core Server Configuration

Heading back to the Ubuntu server where Nagios Core is installed, we’ll configure new services for “rocky” in /usr/local/nagios/etc/objects/hosts.cfg (we configured the host for “rocky” last time). The following script will set up new services to check via the NCPA agent on the Rocky server:

echo "

define service {
    host_name               rocky
    service_description     CPU Usage
    check_command           check_ncpa!-t 'mytoken' -P 5693 -M cpu/percent -w 20 -c 40 -q 'aggregate=avg'
    max_check_attempts      5
    check_interval          5
    retry_interval          1
    check_period            24x7
    notification_interval   60
    notification_period     24x7
    contacts                nagiosadmin
    register                1
}

define service {
    host_name               rocky
    service_description     Memory Usage
    check_command           check_ncpa!-t 'mytoken' -P 5693 -M memory/virtual -w 50 -c 80 -u G
    max_check_attempts      5
    check_interval          5
    retry_interval          1
    check_period            24x7
    notification_interval   60
    notification_period     24x7
    contacts                nagiosadmin
    register                1
}

define service {
    host_name               rocky
    service_description     Process Count
    check_command           check_ncpa!-t 'mytoken' -P 5693 -M processes -w 150 -c 200
    max_check_attempts      5
    check_interval          5
    retry_interval          1
    check_period            24x7
    notification_interval   60
    notification_period     24x7
    contacts                nagiosadmin
    register                1
}

" >> /usr/local/nagios/etc/objects/hosts.cfg

Then we need to download check_ncpa.py from the Nagios github website into /usr/local/nagios/libexec which is the directory where Nagios check scripts go. check_ncpa.py is a script that performs checks on the NCPA agent. This will install it:

wget --no-check-certificate https://raw.githubusercontent.com/NagiosEnterprises/ncpa/master/client/check_ncpa.py -P /usr/local/nagios/libexec/
chmod 755 /usr/local/nagios/libexec/check_ncpa.py #Make accessible and executable
sed -i 's/python/python3/g' /usr/local/nagios/libexec/check_ncpa.py #change 'python' to 'python3'

Then create a command in /usr/local/nagios/etc/objects/commands.cfg that defines the “check_ncpa” command:

echo "

define command {
    command_name    check_ncpa
    command_line    \$USER1\$/check_ncpa.py -H \$HOSTADDRESS\$ \$ARG1\$
}

" >> /usr/local/nagios/etc/objects/commands.cfg

Now reload nagios:

systemctl restart nagios

Remember, if you have any troubles, this command will probably help you out. It’s Nagios Core’s tool to check your config:

/usr/local/nagios/bin/nagios -v /usr/local/nagios/etc/nagios.cfg

Now that we have the new services loaded, let’s see how they show up in the Nagios web interface.

Nagios Core Web Interafce

We should be able to see that “CPU Usage”, “Memory Usage” and “Process Count” are now showing up as services by going to “Hosts” (left nav pane) –> rocky (click on name) –> “View Status Detail For This Host”.

Hope you liked!

Nagios Core 4.4.6 Monitoring on Ubuntu 20.04

Nagios is a time-tested network monitoring tool that network engineers and systems administrators alike have used since its creation in 1999 to monitor networks and alert engineers if something goes wrong. At some point around 2009, Nagios became Nagios Core so that the company could release some more products. Nagios Core remains free and open source, though.

It has many ways to monitor various network nodes, including ping checks, agents and SNMP. Today, we’ll see if we can just get the server and web interface installed, along with a couple basic ping checks.

Let’s get started!

Topology

Topology in GNS3

We’ll monitor across a simple subnet of 172.16.0.0/24. We’ll install Nagios Core on Ubuntu server at the top, and monitor the Rocky Linux and Cisco IOSv router at the bottom.

Installation

While it’s possible to install from the standard Ubuntu repositories, that version is very old and doesn’t seem to work very well out of the box. Building the most recent version from source works the best.

There are a number of steps, so I will include comments inline about what commands we’re entering. To install:

#Install necessary libraries
apt-get update
apt-get install -y autoconf gcc libc6 make wget unzip apache2 php libapache2-mod-php7.4 libgd-dev

#Download Nagios Core
cd /tmp
wget -O nagioscore.tar.gz https://github.com/NagiosEnterprises/nagioscore/archive/nagios-4.4.6.tar.gz

#Extract and enter directory
tar xzf nagioscore.tar.gz

#Compile
cd /tmp/nagioscore-nagios-4.4.6/
./configure --with-httpd-conf=/etc/apache2/sites-enabled
make all

#Set up users
make install-groups-users
usermod -a -G nagios www-data

#Install
make install
make install-daemoninit
make install-commandmode

#Install a sample script config
make install-config

#Install Apache config files
sudo make install-webconf
sudo a2enmod rewrite
sudo a2enmod cgi

#Create a user account for nagios
sudo htpasswd -c /usr/local/nagios/etc/htpasswd.users nagiosadmin

#Restart apache
systemctl restart apache

#Prepare for plugins installation. Need plugins to do anything at all with nagios
sudo apt-get install -y autoconf gcc libc6 libmcrypt-dev make libssl-dev wget bc gawk dc build-essential snmp libnet-snmp-perl gettext

#Download and extract plugins
cd /tmp
wget --no-check-certificate -O nagios-plugins.tar.gz https://github.com/nagios-plugins/nagios-plugins/archive/release-2.3.3.tar.gz
tar zxf nagios-plugins.tar.gz

#Compile plugins and install
cd /tmp/nagios-plugins-release-2.3.3/
./tools/setup
./configure
make
make install

That was a lot! Hopefully you got it installed ok. The nagios web interface can be accessed from http://<fqdn or ip>/nagios. It should look something like this:

Nagios Web Interface

Now that we have it installed, it’s time to set up some monitoring. You’d think this could be done via the web interface but it cannot. It needs to be done from nagios config files.

Monitoring Configuration

There are a number of configuration files, they should all be located in /usr/local/nagios/etc/objects. The nagios program itself is located at /usr/local/nagios/bin/nagios, but the installation process registered a service with systemd, so we’ll mostly be using that. We need to create “hosts”, which are other severs, workstations or routers to monitor. We’ll run this script, I have commented in-line:

#Edit the main nagios config file at /usr/local/nagios/etc/nagios.cfg, add line to add a config file called "hosts.cfg"
echo "cfg_file=/usr/local/nagios/etc/objects/hosts.cfg" >> /usr/local/nagios/etc/nagios.cfg

#Write a config to ping hosts
echo "

define host{
    host_name                       rocky
    alias                           rocky
    address                         172.16.0.2
    check_command                   check-host-alive
    max_check_attempts              5
    check_period                    24x7
    notification_interval           30
    notification_period             24x7
}
define host{
    host_name                       cisco_iosv
    alias                           cisco_iosv
    address                         172.16.0.3
    check_command                   check-host-alive
    max_check_attempts              5
    check_period                    24x7
    notification_interval           30
    notification_period             24x7
}

" >> /usr/local/nagios/etc/objects/hosts.cfg

Before you restart nagios and apply the configuration, you can check to see if there’s any errors using a built-in tool that nagios has:

/usr/local/nagios/bin/nagios -v /usr/local/nagios/etc/nagios.cfg
---
<Edited for brevity>

Total Warnings: 2
Total Errors:   0

Things look okay - No serious problems were detected during the pre-flight check

If there’s any errors, it should give you some advice on how to fix them. Otherwise, restart nagios:

systemctl restart nagios

After the checks run, you should be seeing that your hosts are up by click on “Hosts” on the nav bar to the left:

Nagios is a sizeable piece of software and very extensible. There are many things you can do with it far beyond what we’ve done here. However we’ve gotten the core functionality working – pinging stuff.

We’ll take a look at how to do more than that in the next post. Stay tuned!

Syslog Server on Ubuntu 20.04

Running a syslog server that can collect logs from various devices on your network is really simple with Ubuntu Server 20.04. Using built-in software Rsyslog, you can quickly configure it to be either a syslog client or a server. Since most network devices have the capability to send logs to an external server, you can quickly set up your Ubuntu server act as a central log collection point.

What many folks don’t know is that syslog is actually a standard application-layer network protocol, not just software. It is defined in RFC 5424. It’s because of this standard protocol that network devices and servers alike are able to easily send and store logs. Without a standard protocol, it would be much more difficult to pull that off.

Let’s set up syslog on Ubuntu 20.04!

Topology

Topology in GNS3

The Ubuntu server at 10.0.0.1 will act as our syslog server while the other Ubuntu server and Cisco router will act as clients, sending their logs to the server.

Server Configuration

Since Rsyslog is already installed on Ubuntu (and others), there’s no installation. First we need to edit /etc/rsyslog.conf and uncomment these lines:

module(load="imudp")
input(type="imudp" port="514")

module(load="imtcp")
input(type="imtcp" port="514")

They will activate the server on TCP and UDP port 514 for incoming syslog messages. With just this configuration, the syslog server will work. But we’ll make one more modification – we want each IP address to have it’s own file. Otherwise all messages get dumped in the main file at /var/log/syslog.

We’ll create a file at /etc/rsyslog.d/30-custom.conf and place a couple of simple rules in it:

if $fromhost-ip startswith '10.0.0.2' then /var/log/network/10.0.0.2.log
& stop
if $fromhost-ip startswith '10.0.0.3' then /var/log/network/10.0.0.3.log
& stop

Create and change the ownership of the /var/log/network directory:

mkdir /var/log/network
chown syslog:adm /var/log/network

And restart Rsyslog:

systemctl restart rsyslog

And we’re done!

Client Configuration

For a Cisco IOSv device, the following command will turn on logging to a remote server:

logging host 10.0.0.1

For Ubuntu, just add the following line to /etc/rsyslog.conf:

*.* @@10.0.0.1:514

And restart the service:

systemctl restart rsyslog

Verification

To verify that syslog messages are in fact going to the server, we need to initiate an event.

For Cisco IOSv, shutting/no shutting any interface will do the trick. In config mode on the interface, just issue these commands:

Router(config-if)# shut
Router(config-if)# no shut

While you might be tempted to go check /var/log/network/10.0.0.2.log right away for syslog messages, it might be worth it to do a packet capture first to see if logs are indeed leaving the Cisco router and heading for the syslog server.

A capture between the two shows the following lone packet when we issue those shut commands:

Syslog protocol in Wireshark

Then check the /var/log/network/10.0.0.3.log on the syslog server to see if the message was properly written:

cat /var/log/network/10.0.0.3.log
---
Jan 27 13:48:17 10.0.0.3 45: *Jan 27 13:48:16.540: %LINK-3-UPDOWN: Interface GigabitEthernet0/1, changed state to down

Initiating an event on the Ubuntu client is as easy as shutting down a service (I’m sure there’s others too). I happen to have Nginx web server running on this guy so I’ll stop it:

systemctl stop nginx

The in the file on the syslog server:

cat /var/log/network/10.0.0.2.log
---
Jan 27 23:21:21 u20vm systemd[1]: Stopping A high performance web server and a reverse proxy server...
Jan 27 23:21:21 u20vm systemd[1]: nginx.service: Succeeded.
Jan 27 23:21:21 u20vm systemd[1]: Stopped A high performance web server and a reverse proxy server.

Hope you liked this one.

Suricata IDS/IPS on Ubuntu 20.04

No network security setup would be complete without a network-based Intrusion Detection System and Intrusion Prevention System (IPS/IDS). For many businesses, network-based IDS/IPS is a key component of maintaining a PCI-compliant environment. PCI compliance is mandated for any business that handles credit card-holder data in any way. Other businesses handle such sensitive information that literally every packet needs to be inspected for any kind of malicious activity. Financial institutions, healthcare providers and government bodies usually fall into this category.

Whatever the business need, IDS/IPS (from this point forward, I mean network-based. Host-based is another topic entirely) is yet another necessary security tool for keeping a network environment safe. Today we’ll take a look at suricata, an open-source IDS/IPS system that you can install on Ubuntu 20.04. You can even get free, regularly-updated rule lists for staying up-to-date on the latest threats. Some ruleset providers charge for their lists, but many are provided without charge. Let’s get the basics setup and see how it works!

Topology

Topology in GNS3

We’ll install Suricata on Ubuntu20.04-1, which is acting as a router between the hapless workstation and the Internet. We’ll configure Suricata to listen for threats on the “outside”, or Internet-facing interface, ens3.

Installation

Installation requires setting up the Ubuntu PPA for recent, prebuilt packages. We can add it with this command:

add-apt-repository ppa:oisf/suricata-stable

Then update apt, and install:

apt-get update
apt-get install suricata

Configuration

Now that it’s installed, we need to make a couple of configurations in text files. The first is in /etc/default/suricata, which holds the configuration mode and default interface. You’ll want to change the following lines:

LISTENMODE=nfqueue

IFACE=ens3

LISTENMODE sets whether you want suricata to be in IDS or IPS mode. IDS will passively listen and write an alert to a log file. IPS does that too, but with the option to drop detected threats. In order to perform the drop, packets needs to be sent to the nfqueue processing queue. IFACE is whatever network interface you want suricata to listen on.

Next we need to update our rules with the suricata-update command. You can see what lists are enabled by running suricata-update list-sources, but the default ones will do just fine.

suricata-update

Now we should have a set of rules at /var/lib/suricata/rules/suricata.rules. We’ll use the sed tool to mark some of the rules to drop traffic, with these commands:

sed -i -e '/ATTACK_RESPONSE/ s/^alert/drop/' /var/lib/suricata/rules/suricata.rules 
sed -i -e '/USER_AGENTS/ s/^alert/drop/' /var/lib/suricata/rules/suricata.rules 

Finally, we need to send all packets to the NFQUEUE processing queue so they can be dropped if determined to be malicious. These iptables commands will send all packets to that queue with the exception of port 22, which is usually SSH traffic. That way our SSH session to the server isn’t interrupted:

iptables -I INPUT 1 -p tcp --dport 22 -j NFQUEUE --queue-bypass
iptables -I OUTPUT 1 -p tcp --sport 22 -j NFQUEUE --queue-bypass
iptables -I FORWARD -j NFQUEUE
iptables -I INPUT 2 -j NFQUEUE
iptables -I OUTPUT 2 -j NFQUEUE

And finally reload suricata:

systemctl restart suricata

Verification

Quick note: With the way we set suricata up, you can run these tests either from the Ubuntu server where suricata is installed, or from anything behind it. Either will work. Also please rest assured neither of these tests actually does anything close to malicious.

If we send a normal HTTP request to google.com from the hapless workstation at 192.168.0.2, it should work:

curl http://www.google.com
---
<a bunch of web nonsense output here>

But if we change the HTTP user-agent string to “BlackSun”, suricata will detect this as a malware attack. Apparently BlackSun is some kind of ransomware, but just changing the user-agent string to “BlackSun” isn’t going to do anything at all, other than test whether suricata is working or not. The below command will achieve this goal:

curl -A "BlackSun" http://www.google.com
---
<no response>

Suricata is dropping these packets! Our IPS is working. Let’s check if IDS is working too. Activity is logged at /var/log/suricata/fast.log:

cat /var/log/suricata/fast.log
---
01/20/2022-13:40:00.339281  [Drop] [**] [1:2008983:8] ET USER_AGENTS Suspicious User Agent (BlackSun) [**] [Classification: A Network Trojan was detected] [Priority: 1] {TCP} 192.168.122.142:35444 -> 142.250.207.4:80

Success! We’ve been notified of a network attack. Let’s try another one. The website testmynids.com has a nice test we can run with this command:

curl http://testmynids.org/uid/index.html
---
<no response>

This well send an index.html file containing the output of the id root command, a common way for remote command-and-control servers to execute attacks. Let’s check the log:

cat /var/log/suricata/fast.log
---
01/20/2022-13:44:40.778197  [Drop] [**] [1:2100498:7] GPL ATTACK_RESPONSE id check returned root [**] [Classification: Potentially Bad Traffic] [Priority: 2] {TCP} 13.226.78.68:80 -> 192.168.122.142:37444

Success!

How To Ping Sweep With Python in GNS3

I debated for a long time whether to include coding in my networking blog. But since it seems the future of networking lies in code and automation, I believe it is time for some code.

Today we’ll look at how we can quickly ping sweep a subnet using python. If you are looking for some resources on learning python, you might check out this free ebook on python for network engineers or getting a course on Udemy for python. If you’d like me to create a python learning resource in the future, please let me know in the comments or contact form!

Topology

Topology in GNS3

We’ll use a simple IP subnet of 172.16.0.0/24 to sweep. Connected devices have been placed randomly at 172.16.0.51, 172.16.0.121 and 172.16.0.253. We’ll write the sweep python code on the Ubuntu 20.04 server at 172.16.0.1. Let’s get started!

Simple python ping sweep script

The basic logic of the code will be to loop through all hosts in the 172.16.0.0/24 subnet, from 172.16.0.1 to 172.16.0.254 (.0 and .255 are the network and broadcast addresses, so no need to ping them) and ping each IP address once. If it responds, we’ll print to the CLI that it worked.

We’ll use two modules, ipaddress and subprocess. ipaddress is a handy network tool for working with IP addresses. Knowing where to start and stop in the loop is relatively simple with a /24 subnet, what if it were 172.16.0.0/19? Just incrementing the fourth octet by 1 each time won’t work. You’ll go to 172.16.0.256, which isn’t a valid IP address. That’s where ipaddress helps out. subprocess lets us call the ping command from python.

Here’s our code:

import ipaddress
import subprocess

mynet = ipaddress.ip_network('172.16.0.0/24') #create an ipaddress object for 172.16.0.0/24

for host in mynet.hosts():                    #loop through each host of 172.16.0.0/24
    host = str(host)                          #change from ipaddress object to string to hand to ping command
    proc = subprocess.run(                    #use subprocess to call ping command, split to multiple lines cuz its long
        ['ping', host, '-c', '1'],            #calling ping here, putting in host to ping
        stderr=subprocess.DEVNULL,            #silence ping command errors
        stdout=subprocess.DEVNULL             #silence ping command output
        )
    if  proc.returncode == 0:                 #return code of 0 from ping command means it got a reply
        print(f'{host} is alive!')            #say this host is alive if we got a reply

Hopefully this is pretty straightforward. The magic is happening in a couple spots. The first is with this line:

mynet = ipaddress.ip_network('172.16.0.0/24')

This creates an “object” that holds the network we’re working with. This object has super powers, one of them is visible in this line:

for host in mynet.hosts():

It lets us move through the hosts of the subnet, from 172.16.0.1 to 172.16.0.254, each time the host IP is assigned to host. We can then hand host to the ping command.

The second spot with magic is here:

    proc = subprocess.run( 
        ['ping', host, '-c', '1'],
        stderr=subprocess.DEVNULL, 
        stdout=subprocess.DEVNULL 
        )

This is just spawning another process, ping, from python.

When we run the script, we should see all the IP addresses that are alive!

python3 ping_sweep.py #might be python or python3 based on your OS

172.16.0.1 is alive!
172.16.0.51 is alive!
172.16.0.121 is alive!
172.16.0.253 is alive!

There’s only one problem – the script takes quite a while to run. The issue is that each time the ping command runs, python waits until it finishes before moving to the next. This is known as “blocking”, which basically means the script comes to a halt while it’s waiting for a ping process to finish. A common /24 size subnet of 254 hosts takes a good while to complete.

What if we could ping them all at the same time, or close to it? Well, this leads us into the dark, dangerous world of multi-threading, parallel processing, multiprocessing, and asynchronous processing. Even the words are ominous-sounding. But don’t worry, it’s not so bad with the help of a handy module called asyncio.

Super-charged ping sweep with asyncio

The issue we’re faced with is that we need to do multiple things at once. There are many ways to solve this problem, and some people spend their whole careers in this complex field. Recently though, the python asyncio is getting popular because it’s relatively easy to work with and not so terribly complicated compared to others. As of python 3.6, it’s part of the standard library.

Here’s the same ping sweep, this time written using the python asyncio module:

import ipaddress
import asyncio

async def ping(host):                              #add the "async" keyword to make a function asynchronous
    host = str(host)                               #turn ip address object to string
    proc = await asyncio.create_subprocess_shell(  #asyncio can smoothly call subprocess for you
            f'ping {host} -c 1',                   #ping command
            stderr=asyncio.subprocess.DEVNULL,     #silence ping errors
            stdout=asyncio.subprocess.DEVNULL      #silence ping output
            )
    stdout,stderr = await proc.communicate()       #get info from ping process
    if  proc.returncode == 0:                      #if process code was 0
        print(f'{host} is alive!')                 #say it's alive!

loop = asyncio.get_event_loop()                    #create an async loop
tasks = []                                         #list to hold ping tasks

mynet = ipaddress.ip_network('172.16.0.0/24')      #ip address module
for host in mynet.hosts():                         #loop through subnet hosts
    task = ping(host)                              #create async task from function we defined above
    tasks.append(task)                             #add task to list of tasks

tasks = asyncio.gather(*tasks)                     #some magic to assemble the tasks
loop.run_until_complete(tasks)                     #run all tasks (basically) at once

No denying it, this is more complicated. Might be a bit foreign even if you’re familiar with python. The key thing here is that we define a single ping task in an async function. Then when we loop through the subnet hosts, we create a task from that function, instead of running it on the spot. Then we call the asyncio module at the end to gather up the tasks and run them all asynchronously, which has the effect of appearing to run them all at once.

Also note that there’s no subprocess module here. Asyncio has built-in subprocess management (check the documentation here), so no need for the standard subprocess module.

While the output is the same, you’ll notice this takes about a second to run compared to minutes for the first script:

python3 ping_sweep.py

172.16.0.1 is alive!
172.16.0.51 is alive!
172.16.0.121 is alive!
172.16.0.253 is alive!

Please let me know in the comments if you want to see more content like this!

IPv6: IPsec Not Mandatory to Use or Exist

One thing is clear, there is a serious amount of misinformation about IPv6. There are many blog posts and even official documents from respected sources that have blatantly incorrect information. Many blog posts that start out with an introduction such as this one, but end up spreading misinformation about IPv6 anyway. To avoid spreading misinformation myself, I’m going to cite the only sources of truth in the network world: the IETF RFC’s. If you’re looking for a clear and simple one-liner to sum up this article here it is:

Since the IETF issued RFC 6434 in 2011, the IPv6 standard does not require devices to implement (to be capable of) IPsec, nor does it require the enablement or use of IPsec for IPv6 nodes that do implement (are capable of) IPsec.

Yes, you read that right. You cannot count on IPsec even existing in nodes and devices running IPv6. For many years now a great number of sources have been trumpeting that IPv6 will herald an era of not having to think about network security anymore. Most respectable sources reject this notion, saying that it’s required to be implemented (to exist) in all IPv6 nodes, but not required to be turned on. Unfortunately that is also false.

RFC 1883 – where it all started

In December 1995, the IETF (Internet Engineering Task Force, a standards body accepted as the source of truth in the networking world) released RFC 1883, which defined IPv6 as a successor to IPv4.

Page 36 of that RFC briefly and quietly stated that Authentication Header (AH) and Encapsulating Security Payload (ESP) be required to secure IPv6 traffic:

This document specifies that the IP Authentication Header [RFC-1826] and the IP Encapsulating Security Payload [RFC-1827] be used with IPv6, in conformance with the Security Architecture for the Internet Protocol [RFC-1825].

https://datatracker.ietf.org/doc/html/rfc1883

This lead to a lot of folks being really excited about the ramifications of mandated secure connections in IPv6. While I can’t find any articles from 1995, this blog post from Bitdefender (a respected name in security) from 2012 is a really good example of an article making really misleading statements about how IPsec works with IPv6:

IPv6 comes with built-in IPSec , a technology that ensures secure host-to-host communication. This means that two clients communicating over IPv6 can automatically do authentication, message integrity and encryption or any combination of those.

https://www.bitdefender.com/blog/hotforsecurity/ipv6-is-here-ready-to-embrace-it

While the implementation (the capability) of IPsec was indeed mandatory in IPv6 for the first 16 years after RFC 1883 was released, no one ever said that the use or enablement of it would be mandatory.

RFC 6434 – IPsec from MUST to SHOULD

In December 2011, the IETF updated the IPv6 Node Requirements RFC with RFC 6434. In section 11 (Security), they make this unmistakable statement:

Previously, IPv6 mandated implementation of IPsec and recommended the key management approach of IKE. This document updates that recommendation by making support of the IPsec Architecture [RFC4301] a SHOULD for all IPv6 nodes.

https://datatracker.ietf.org/doc/html/rfc6434

While IPv6 IPsec is implemented (the capability exists) in major desktop/laptop OS’s such as Windows and macOS, the Internet is made up of much more than that. Internet of Things comes to mind.

It seems the IETF realized that it doesn’t make sense (or in many cases it’s not possible) to include the complexity of IPsec in an IPv6 implementation. They went on to say in RFC 6434:

This document recognizes that there exists a range of device types and environments where approaches to security other than IPsec can be justified.

https://datatracker.ietf.org/doc/html/rfc6434

Loads of misinformation

So yes, starting in 2011, IPsec even existing in a device running IPv6 is a big maybe. Despite this, some of the most respected companies in the world write documentation that describe the mandatory-ness of IPsec in IPv6. Take this IOS configuration guide from Cisco, written in August 2012:

IPsec is a mandatory component of IPv6 specification.

https://www.cisco.com/c/en/us/td/docs/ios-xml/ios/ipv6/configuration/15-2s/ipv6-15-2s-book/ip6-ipsec.html

Or this article from Microsoft written in 2020:

Internet Protocol Security (IPsec) is a set of security protocols used to transfer IP packets confidentially across the Internet. IPsec is mandatory for all IPv6 implementations and optional for IPv4.

https://docs.microsoft.com/en-us/windows/win32/fwp/ipsec-configuration

Or this article from Redhat written in 2019:

In What you need to know about IPv6, we mentioned that Internet Protocol Security (IPSec) is incorporated into IPv6. This statement simply means that communication between the two endpoints is either authenticated, encrypted, or both, via the extension headers. There is a long-running discussion on the internet regarding whether the interpretation of “IPSec being mandatory” in IPv6 is correct or not. If you need to know more about this topic, see RFC 6434.

https://www.redhat.com/sysadmin/ipv6-packets-and-ipsec

This last one from Redhat is particularly confusing. They mention the very RFC where IPsec became optional and even mention the ongoing debate, but continue to say that communications in IPv6 are either authenticated or encrypted, or both.

What’s actually happening? Not IPv6 IPsec.

All of this RFC and protocol stuff is a bunch of theoretical pie in the sky. What’s actually happening out in the wild? Well, I can’t speak to the whole Internet. Maybe folks are using IPsec like they do in IPv4 – for site-to-site tunnels. Or maybe something else. But to test typical web traffic, I have native IPv6 capability in my home. I took some Wireshark captures to various websites.

Here’s google.com:

IPv6 capture of google.com

Here’s microsoft.com:

IPv6 capture of microsoft.com

Here’s wikipedia.org:

IPv6 capture of wikipedia.org

Where’s the IPsec? I don’t see any IKE, AH or ESP. Looks like typical TLS traffic to me. So… no change in security from IPv4, then.

iperf2 vs iperf3: What’s the difference?

At first glance, you might be tempted to use iperf3 simply because it is one more than iperf2 (don’t worry, I’m guilty of this crime as well). It’s not an unfair assumption to think that iperf3 is the most recent version of the software, because of the name. It’s common to have two different versions of software in parallel existence, so the new one can take hold while the older version slowly dies away. Python2 and Python3 come to mind. This is not the case with iperf, however.

I recently wrote a post on how to use iperf3 to test bandwidth. Shortly after that one of the authors of iperf2, Bob McMahon, reached out to me. He pointed out that iperf2 is very much actively developed with some cool new features having been added recently. Under the surface they are very different projects, maintained by different teams with different goals.

Today we’ll take a look at some of the differences between the two.

Topology

Ubuntu 20.04 and Rocky Linux 8.5 VM’s in GNS3

We have a really basic topology here, Ubuntu 20.04 and Rocky Linux 8.5 connected on a single link with IP subnet 10.0.0.0/30. Both VM’s have iperf2 and iperf3 installed.

Bandwidth Test

For a bandwidth test, the two are almost identical. You can perform a bandwidth test using either with the same commands. For this test, the Ubuntu VM will be the client, and Rocky the server. Start the server on Rocky like this:

iperf -s

------------------------------------------------------------
Server listening on TCP port 5001
TCP window size: 85.3 KByte (default)
------------------------------------------------------------

And from Ubuntu perform a test like this:

iperf -c 10.0.0.2
------------------------------------------------------------
Client connecting to 10.0.0.2, TCP port 5001
TCP window size:  238 KByte (default)
------------------------------------------------------------
[  3] local 10.0.0.1 port 36528 connected with 10.0.0.2 port 5001
[ ID] Interval       Transfer     Bandwidth
[  3]  0.0-10.0 sec  1.90 GBytes  1.63 Gbits/sec

These commands will work using iperf2 or iperf3, however it should be noted you can’t use an iperf2 client with an iperf3 server, and vice-versa. Also, they use different TCP ports by default. Even if you used an iperf3 client with an iperf2 server and manually set the TCP port to be the same, you will get an error. They are not compatible:

iperf3 -c 10.0.0.2 -p 5001
iperf3: error - received an unknown control message

Supported Operating Systems

iperf2 is the clear winner here, primarily because it has up-to-date Windows packages available for easy download right on the sourceforge page. I avoid Windows when I can, but it has a tendency to be unavoidable due to it’s sheer installation base. iperf3 apparently had some unofficial builds a while back but nothing officially supported. You’ll need to compile it yourself to work on Windows which can be an inconvenience at best.

iperf2 downloads page

For Linux, many operating systems come with iperf2 preinstalled, Ubuntu 20.04 is one such example. iperf3 is just a command away though, with package managers. For macOS, the Homebrew package manager can quickly get you iperf2 or iperf3.

Feature: iperf3 authentication (not encryption)

Description of authentication features in iperf3

iperf3 supports authenticating clients to the server using public key/private key as well as a users file. I decided to try it out. To avoid a hassle I just used the exact commands they provided in the man file. You first generate a public key and private key on the server:

openssl genrsa -des3 -out private.pem 2048
openssl rsa -in private.pem -outform PEM -pubout -out public.pem
openssl rsa -in private.pem -out private_not_protected.pem -outform PEM

Then create a “credentials.csv” file with hashed passwords. The following commands will get a hashed password for you:

S_USER=james S_PASSWD=james
echo -n "{$S_USER}$S_PASSWD" | sha256sum | awk '{ print $1 }'
----
0b0c98028105e9e4d3f100280eac29bba90af614d1c75612729228e4d160c601 #This is the hash of "james"

Then create a “credentials.csv” file that looks like this:

username,sha256
james,0b0c98028105e9e4d3f100280eac29bba90af614d1c75612729228e4d160c601

Now start the server:

iperf3 -s --rsa-private-key-path ./private_not_protected.pem --authorized-users-path ./credentials.csv

Then from the client, copy the public key over:

scp james@10.0.0.1:public.pem .

Then run the client:

iperf3 -c 10.0.0.1 --rsa-public-key-path ./public.pem --username james

You’ll be asked for the password. If you get it right, the server will display a message that authentication succeeded:

-----------------------------------------------------------
Server listening on 5201
-----------------------------------------------------------
Authentication successed for user 'james' ts 1639396545
Accepted connection from 10.0.0.2, port 32784
[  5] local 10.0.0.1 port 5201 connected to 10.0.0.2 port 32786
[ ID] Interval           Transfer     Bitrate
[  5]   0.00-1.00   sec   194 MBytes  1.63 Gbits/sec                  
[  5]   1.00-2.00   sec   204 MBytes  1.71 Gbits/sec

Feature: iperf2 isochronous mode

One of the coolest features of iperf2 is its “isochronous” option. This option is designed to simulate video streaming network traffic. You can hear Bob McMahon explain it himself on his youtube video on this feature.

Using the parameters and commands he describes in his video, we’ll run on a test. The Ubuntu server will be the iperf2 server:

iperf -s -e -i 1

Then on Rocky Linux we’ll run the client test:

[james@localhost ~]$ iperf -c 10.0.0.1 -i 1 --isochronous=60:40m,10m
------------------------------------------------------------
Client connecting to 10.0.0.1, TCP port 5001 with pid 1640
UDP isochronous: 60 frames/sec mean=40.0 Mbit/s, stddev=10.0 Mbit/s, Period/IPG=16.67/0.005 ms
TCP window size:  340 KByte (default)
------------------------------------------------------------
[  3] local 10.0.0.2 port 49150 connected with 10.0.0.1 port 5001 (ct=1.44 ms)
[ ID] Interval        Transfer    Bandwidth       Write/Err  Rtry     Cwnd/RTT        NetPwr
[  3] 0.00-1.00 sec   214 MBytes  1.79 Gbits/sec  1708/0          0       67K/562 us  398346.93
[  3] 1.00-2.00 sec   217 MBytes  1.82 Gbits/sec  1738/0        230      145K/608 us  374676.21
[  3] 2.00-3.00 sec   205 MBytes  1.72 Gbits/sec  1640/0        427      142K/583 us  368710.26
[  3] 3.00-4.00 sec   212 MBytes  1.78 Gbits/sec  1697/0        575      118K/920 us  241770.85
[  3] 4.00-5.00 sec   200 MBytes  1.68 Gbits/sec  1599/0        371      134K/853 us  245702.38
[  3] 5.00-6.00 sec   200 MBytes  1.68 Gbits/sec  1598/0        423      117K/529 us  395941.50

On the server we get our output:

james@u20vm:~$ iperf -s -e -i 1
------------------------------------------------------------
Server listening on TCP port 5001 with pid 3045
Read buffer size:  128 KByte
TCP window size:  128 KByte (default)
------------------------------------------------------------
[  4] local 10.0.0.1 port 5001 connected with 10.0.0.2 port 49150
[ ID] Interval            Transfer    Bandwidth       Reads   Dist(bin=16.0K)
[  4] 0.0000-1.0000 sec   213 MBytes  1.79 Gbits/sec  4631    503:1500:1008:577:276:191:138:438
[  4] 1.0000-2.0000 sec   217 MBytes  1.82 Gbits/sec  4018    570:838:812:502:255:231:164:646
[  4] 2.0000-3.0000 sec   204 MBytes  1.71 Gbits/sec  5074    590:1537:1637:511:316:152:115:216
[  4] 3.0000-4.0000 sec   212 MBytes  1.78 Gbits/sec  3924    599:805:717:464:266:264:246:563
[  4] 4.0000-5.0000 sec   200 MBytes  1.68 Gbits/sec  3876    575:953:672:462:258:242:188:526
[  4] 5.0000-6.0000 sec   200 MBytes  1.68 Gbits/sec  4046    656:1040:687:476:258:242:238:449

Unfortunately the version of iperf that is available in Ubuntu 20.04 repositories (2.0.13) doesn’t support isochronous TCP mode mentioned in the video. You would need to compile from source or use Windows for that. A newer version will be included (probably already has been by the time you’re reading this) in Ubuntu 22.04 LTS.

Various smaller differences

There are many other spots that iperf2 and iperf3 are different.

  • iperf2 supports an “enhanced output mode” using -e that is totally revamped (used it above in the isochronous section).
  • iperf3 supports json output using the -j option.
  • iperf2 supports a bidirectional test which performs tests from the client and server simultaneously using -d
  • iperf2 uses a multi-threaded architecture, while iperf3 uses single-threaded. To be honest, I haven’t seen any way that this actually affects performance of the application. I’d be really curious if anyone has some input on this.

I hope this was helpful, and I hope I did both of these cool programs a small amount of justice. I’m really curious to see if anyone has any other input or differences they know about. Please fee free to comment or reach out directly.

How To Install Free Range Routing (FRR) on Ubuntu 20.04 and Rocky Linux 8.5

The latest version of my favorite routing protocol software, Free Range Routing 8.1 was recently released on November 9th.

Free Range Routing is a fork of the Quagga project that improves upon it and adds lots more features and new protocols. My favorite protocol that is added is EIGRP, which was originally a Cisco proprietary protocol until Cisco released a draft RFC in 2013. Free Range Routing makes it easy to spin up a Linux router and exchange routes via EIGRP. Since Cisco routers speak EIGRP, you can also exchange routes with them too! Today we’ll just exchange routes between Ubuntu 20.04 and Rocky Linux 8.5 via EIGRP.

Topology

Ubuntu and Rocky Linux in GNS3

We have a simple network here with an Ubuntu and Rocky Linux VM’s acting as IP routers. Without adding routes, Ubuntu does not know about 172.16.0.0/24, and Rocky does not know about 192.168.0.0/24. EIGRP can educate them. I should mention – each of the Alpine nodes has a default route pointing to the .1 in their subnet (Ubuntu and Rocky), which is a typical setup in most networks.

Installation

In a previous post, I installed FRR on Ubuntu 18.04 via the snap store. You can still do that, but it looks like the snap version hasn’t been updated with 8.1. I’m sure it will be updated soon, but let’s install it via the binary packages that FRR provides just to do something different.

For Rocky Linux, you can find instructions here. They are RPM packages for CentOS, and in my testing I found them to work fine for Rocky Linux. Per their instructions, we’ll run these commands:

FRRVER="frr-stable"
curl -O https://rpm.frrouting.org/repo/$FRRVER-repo-1-0.el8.noarch.rpm
sudo yum install ./$FRRVER*
sudo yum install frr frr-pythontools

We’ll need to modify /etc/frr/daemons and turn on the protocols we want, in this case EIGRP:

vi /etc/frr/daemons
---

eigrpd=yes #find this line and set to yes

Then you’ll need to restart frr:

systemctl restart frr

The process is similar on Ubuntu. The debian-based instructions are on this page. Following those, we’ll run these commands:

curl -s https://deb.frrouting.org/frr/keys.asc | sudo apt-key add -
FRRVER="frr-stable"
echo deb https://deb.frrouting.org/frr $(lsb_release -s -c) $FRRVER | sudo tee -a /etc/apt/sources.list.d/frr.list
sudo apt update && sudo apt install frr frr-pythontools

We’ll need do modify the daemons file similar to above and run the exact same systemctl command to restart frr.

Installation is complete!

Configure FRR and EIGRP

To setup EIGRP routing, we’ll enter the FRR vtysh configuration tool that should be familiar if you’ve used either Quagga or Cisco IOS routers. On Ubuntu we’ll do this:

vtysh
---

Hello, this is FRRouting (version 8.1).
Copyright 1996-2005 Kunihiro Ishiguro, et al.

u20vm# conf t
u20vm(config)# router eigrp 10
u20vm(config-router)# network 10.0.0.0/30
u20vm(config-router)# network 192.168.0.0/24
u20vm(config-router)# ^Z
u20vm# exit

On Rocky Linux, it’s almost exactly the same but the second network to add is 172.16.0.0/24:

vtysh
---

Hello, this is FRRouting (version 8.1).
Copyright 1996-2005 Kunihiro Ishiguro, et al.

rl85vm# conf t
rl85vm(config)# router eigrp 10
rl85vm(config-router)# network 10.0.0.0/30
rl85vm(config-router)# network 172.16.0.0/24
rl85vm(config-router)# ^Z
rl85vm# exit

Since Rocky is runnning firewalld by default, you’ll need to either stop it with systemctl stop firewalld or go through the process to allow EIGRP-related traffic through the firewall.

We should be able to see that each router has the other’s connected route now installed in its table. On Ubuntu we can see 172.16.0.0/24 is installed from vtysh with show ip route (edited somewhat for brevity):

u20vm# show ip route
---

E   10.0.0.0/30 [90/28160] is directly connected, ens3, weight 1, 00:41:19
C>* 10.0.0.0/30 is directly connected, ens3, 00:41:57
E>* 172.16.0.0/24 [90/30720] via 10.0.0.2, ens3, weight 1, 00:40:55
E   192.168.0.0/24 [90/28160] is directly connected, ens4, weight 1, 00:40:43
C>* 192.168.0.0/24 is directly connected, ens4, 00:41:57

And likewise on Rocky Linux we can see 192.168.0.0/24 is installed:

rl85vm# show ip route
---

E   10.0.0.0/30 [90/28160] is directly connected, ens3, weight 1, 00:43:07
C>* 10.0.0.0/30 is directly connected, ens3, 00:43:45
E   172.16.0.0/24 [90/28160] is directly connected, ens4, weight 1, 00:42:50
C>* 172.16.0.0/24 is directly connected, ens4, 00:43:45
E>* 192.168.0.0/24 [90/30720] via 10.0.0.1, ens3, weight 1, 00:42:38
localhost.localdomain# 

A wireshark (if you’re running GNS3) will show the EIGRP messages flowing. If you catch it right at the start, you can see updates messages and not just hellos:

Wireshark capture of EIGRP traffic between Ubuntu and Rocky Linux

Verify

This should be easy, we’ll just ping between the Alpine Linux nodes. (make sure each has a default route pointing to .1)

/ # ping 172.16.0.1
PING 172.16.0.1 (172.16.0.1): 56 data bytes
64 bytes from 172.16.0.1: seq=0 ttl=63 time=2.662 ms

It works!

Hope you liked it.

How To Test Network Bandwidth With iperf3 in Linux

Testing network bandwidth in multiple flavors in Linux is simple with a tool called iperf. There’s two main versions – iperf2 and iperf3. Project maintainers apparently completely rewrote iperf3 from scratch to make the the tool simpler and to support some new features.

Update 12/12/2021: One of the authors of iperf2 reached out to me. Iperf2 is currently very much actively developed. You can find the most recent code on its sourceforge.net page. Iperf3 was indeed rewritten from scratch as the wikipedia page says, but mostly to meet the U.S. Department of Energy’s use cases. Iperf3’s github page clearly states the the DoE owns the project.

For testing bandwidth properly, you need to be running in server mode on one endpoint and client mode on the other. For this experiement, we will run the server on Rocky Linux 8.5 and the client on Ubuntu 20.04.

Topology

iperf3 test in GNS3

This is about as simple of a topology as I can think of. Two nodes on either end of a single link, Ubuntu at 10.0.0.1/30 running iperf3 client and Rocky at 10.0.0.2/30 running iperf3 server.

Iperf3 installation

On Ubuntu, iperf3 can be installed from distribution sources with apt-get:

apt-get install iperf3

Same on Rocky Linux but with yum:

yum install iperf3

Run iperf3 bandwidth test

First we need to start the server process on Rocky Linux with one command:

iperf3 -s

Then you should see the server listening for incoming tests:

iperf3 server listening on Rocky Linux 8.5

Then from the Ubuntu client, one command will run the test:

iperf3 -c 10.0.0.2

The output will give us our bandwith test results, which can be see on either the client or server:

Connecting to host 10.0.0.2, port 5201
[  5] local 10.0.0.1 port 59628 connected to 10.0.0.2 port 5201
[ ID] Interval           Transfer     Bitrate         Retr  Cwnd
[  5]   0.00-1.00   sec   176 MBytes  1.48 Gbits/sec  685    230 KBytes       
[  5]   1.00-2.00   sec   173 MBytes  1.45 Gbits/sec  738    113 KBytes       
[  5]   2.00-3.00   sec   170 MBytes  1.42 Gbits/sec  1004    191 KBytes       
[  5]   3.00-4.00   sec   175 MBytes  1.47 Gbits/sec  714    123 KBytes       
[  5]   4.00-5.00   sec   182 MBytes  1.52 Gbits/sec  458    163 KBytes       
[  5]   5.00-6.00   sec   204 MBytes  1.71 Gbits/sec  443    314 KBytes       
[  5]   6.00-7.00   sec   180 MBytes  1.51 Gbits/sec  910    130 KBytes       
[  5]   7.00-8.00   sec   191 MBytes  1.60 Gbits/sec  849    123 KBytes       
[  5]   8.00-9.00   sec   172 MBytes  1.44 Gbits/sec  564    170 KBytes       
[  5]   9.00-10.00  sec   184 MBytes  1.54 Gbits/sec  412    225 KBytes       
- - - - - - - - - - - - - - - - - - - - - - - - -
[ ID] Interval           Transfer     Bitrate         Retr
[  5]   0.00-10.00  sec  1.76 GBytes  1.52 Gbits/sec  6777             sender
[  5]   0.00-10.04  sec  1.76 GBytes  1.51 Gbits/sec                  receiver

iperf Done.

A wireshark capture in GNS3 between the two hosts (or tcpdump on the links if you’re not in GNS3) will show the packets flying while the test is running:

Wireshark capture from GNS3 of iperf3 test

Hope you liked it!