Hack and / - Dynamic Config Files with Nmap

by Kyle Rankin
Nmap

The great thing about tools is that you often can misuse them for a completely different purpose. The end of a screwdriver makes a passable hammer; a butter knife can be a screwdriver, and even a paper clip can substitute for a key in a pinch. Normally, you probably think of nmap as a security tool. After all, it's ideal when you want to test a machine for open, vulnerable ports. The other day though, I realized nmap had another use—a way to scan my network and build a dynamic configuration file based on what machines replied to my scan.

Munin Is Trendy

This whole project started when I decided to deploy Munin across my servers so I could graph trending data for each machine on my network. Munin is a great tool for trending, because once you install the agent, it often will discover what services and statistics to monitor and graph automatically. The downside for me though was that I already had a network full of servers. It was bad enough that I had to install an agent on each machine, but I also had to build a giant configuration file on my Munin server by hand that listed each server it should monitor. Plus, any time I added a machine to the network, I had yet another step in my build process as I had to add that new server to my Munin config.

I'm a big fan of automation, and I figured there must be some easier way to add all my machines to this file. When you look at a Munin configuration file, it seems ripe for automation:

dbdir   /var/lib/munin
htmldir /var/www/munin
logdir  /var/log/munin
rundir  /var/run/munin
tmpldir /etc/munin/templates

[web1.example.net]
        address web1.example.net

[web2.example.net]
        address web2.example.net

[db1.example.net]
        address db1.example.net

[db2.example.net]
        address db2.example.net

The syntax for a generic munin.conf file is pretty straightforward. First, a few directories are defined, and then each server is defined within a pair of brackets. Inside those brackets, you can assign a name to the server or just use the hostname. After that, the following line lists the hostname or IP address for that server. In the above example, I've defined four servers.

If I wanted to generate this configuration file automatically, I had to figure out some way to detect what servers were running Munin on my network. Munin makes this simple though, because each server has a Munin agent listening on port 4949 by default. All I had to do was use nmap to scan the network and list all the machines that had port 4949 open. I figured I could parse that output and append it to my munin.conf file, and then maybe make a vim macro to go through each line and format it.

Nmap with Grepable Output

The first step was to find the right nmap syntax so that it would scan my network and list all machines that were listening to port 4949. First, I tried the standard command:

$ nmap -p 4949 10.1.1.0/24

Starting Nmap 4.11 ( https://www.insecure.org/nmap/ ) 
 ↪at 2010-03-01 20:18 PST

Interesting ports on 10.1.1.1:
PORT     STATE  SERVICE
4949/tcp closed unknown
MAC Address: 00:00:0C:01:CD:05 (Cisco Systems)

Interesting ports on purple1.example.net (10.1.1.50):
PORT     STATE  SERVICE
4949/tcp closed unknown
MAC Address: 08:00:20:CF:9D:D7 (SUN Microsystems)

Interesting ports on web1.example.net (10.1.1.53):
PORT     STATE SERVICE
4949/tcp open  unknown
MAC Address: 00:50:56:92:34:02 (VMWare)

Interesting ports on web2.example.net (10.1.1.67):
PORT     STATE SERVICE
4949/tcp open  unknown
MAC Address: 00:30:48:A0:12:98 (Supermicro Computer)
. . .

As you can see, for each machine that nmap finds, it lists the IP, whether the port is open, and even tries to identify the type of machine. Even though you could grep out the machines with open ports from this output, it would be quite a pain to parse everything with the multiline output. Instead, I used the -oG argument to nmap, which tells it to output in “grepable format”, along with the - argument, which tells it to send that output to STDOUT. The result was much simpler to parse:

$ nmap -oG - -p 4949 10.1.1.0/24
# Nmap 4.11 scan initiated Mon Mar  1 20:26:45 2010 as: 
 ↪nmap -oG - -p 4949
# 10.1.1.0/24 
Host: 10.1.1.1 ()      Ports: 4949/closed/tcp/////
Host: 10.1.1.50 (purple1.example.net)    Ports: 4949/closed/tcp/////
Host: 10.1.1.53 (web1.example.net)       Ports: 4949/open/tcp/////
Host: 10.1.1.67 (web2.example.net)       Ports: 4949/open/tcp/////
. . .

Now I could just grep for “open”, and I'd get a list of all machines running Munin:

$ nmap -oG - -p 4949 10.1.1.0/24 | grep open
Host: 10.1.1.53 (web1.example.net)     Ports: 4949/open/tcp/////
Host: 10.1.1.67 (web2.example.net)     Ports: 4949/open/tcp/////
Perl to the Rescue

Once I started working on the regular expressions to parse through this output and generate the syntax I needed, I realized I should ditch vim and just write a script that built the entire configuration file for me and run that script with cron. That way, I'd never have to add a new server again. The only challenge was that I had multiple subnets I wanted to scan, and I discovered that sometimes nmap didn't resolve the IP addresses into hostnames for me. Listing 1 shows the resulting script.

Listing 1. Script to Build Configuration File

#!/usr/bin/perl

my $munin_dir = '/etc/munin';
my $munin_config = 'munin.conf';
my $munin_config_temp = 'munin.conf.tmp';
my $node_port = '4949';
my $nmap = "nmap -oG - -p ";
my %subnets = ( 
                "10.1.1.0/24" => "VLAN1",
                "10.1.5.0/24" => "VLAN5",
                "10.1.6.0/24" => "VLAN6",
             );

# iterate through each subnet and perform the nmap scan
foreach $subnet (keys %subnets){
   open NMAP, "$nmap $node_port $subnet | grep open |" 
   ↪or die "Can't run nmap: $!\n";
   while (<NMAP>){
      $ip = $host = "";
# parse out the hostname and IP address
      /Host: (\d+\.\d+\.\d+\.\d+) \((.*?)\)/;
      $ip = $1; $host = $2;

      next if($ip eq "");

# sometimes nmap doesn't do rDNS properly, 
# get it manually in that case
      if($host eq ""){
         $host = `dig -x $ip +short` or $host = $ip;
         chomp $host;
         $host =~ s/\.$//;
      }

      $munin_hosts{$host} = $ip;
   }
   close NMAP;
}

# output to a temp file in case munin 
# runs while this script is open
open OUTFILE, "> $munin_dir/$munin_config_temp" or die "Can't open
$munin_dir/$munin_config_temp: $!\n";

# first print out the standard header for the munin file
print OUTFILE <<END_HEAD;
dbdir   /var/lib/munin
htmldir /var/www/munin
logdir  /var/log/munin
rundir  /var/run/munin
tmpldir /etc/munin/templates

END_HEAD

# then print out the config for each host
foreach $host (sort keys %munin_hosts){
   print OUTFILE "\[$host\]\n\taddress $host\n";
   # add any extra munin options for each host here
   print OUTFILE "\n";
}
close OUTFILE;

system("mv $munin_dir/$munin_config_temp $munin_dir/$munin_config");

Other than the hashes and a little fun with regular expressions, the bulk of this script is basic Perl. Once I tested it a few times by hand and was comfortable with it, I went ahead and copied the script into /etc/cron.daily. Of course, on my real network, I've added a few other fancy touches. For instance, every server on my network has a DNS TXT record that says what the server does. It is a useful practice for many reasons, but in this case, I found that because I used the same TXT record for similar servers, I could look it up and use that to group servers together under that heading.

Although this script worked great for Munin configs, you also could use the same procedure to scan for any number of services and build a configuration. I could see scripts that generate configuration files for Nagios, programs that poll SNMP or any other program that monitors multiple servers over a known port.

Kyle Rankin is a Systems Architect in the San Francisco Bay Area and the author of a number of books, including The Official Ubuntu Server Book, Knoppix Hacks and Ubuntu Hacks. He is currently the president of the North Bay Linux Users' Group.

Load Disqus comments