Nmap Network Scanning
Nmap Network Scanning
Nmap Network Scanning is the official guide to the Nmap Security Scanner, a free and open
source utility used by millions of people for network discovery, administration, and security
auditing. From explaining port scanning basics for novices to detailing low-level packet crafting
methods used by advanced hackers, this book suits all levels of security and networking
professionals. A 42-page reference guide documents every Nmap feature and option, while the rest
of the book demonstrates how to apply those features to quickly solve real-world tasks. Examples
and diagrams show actual communication on the wire.
Introduction
Nmap Overview and Demonstration
Avatar Online
Saving the Human Race
MadHat in Wonderland
The Phases of an Nmap Scan
Legal Issues
Is Unauthorized Port Scanning a Crime?
Can Port Scanning Crash the Target Computer/Networks?
Nmap Copyright
The History and Future of Nmap
Introduction
Nmap (“Network Mapper”) is a free and open source utility for
network exploration and security auditing. Many systems and
network administrators also find it useful for tasks such as network
inventory, managing service upgrade schedules, and monitoring
host or service uptime. Nmap uses raw IP packets in novel ways to
determine what hosts are available on the network, what services
(application name and version) those hosts are offering, what
operating systems (and OS versions) they are running, what type of
packet filters/firewalls are in use, and dozens of other
characteristics. It was designed to rapidly scan large networks, but
works fine against single hosts. Nmap runs on all major computer
operating systems, and both console and graphical versions are
available.
Avatar Online
Being the careful type, Felix first starts out with what is known as an
Nmap list scan (-sL option). This feature simply enumerates every IP
address in the given target netblock(s) and does a reverse-DNS
lookup (unless -n was specified) on each. One reason to do this first
is stealth. The names of the hosts can hint at potential
vulnerabilities and allow for a better understanding of the target
network, all without raising alarm bells[4]. Felix is doing this for
another reason—to double-check that the IP ranges are correct. The
systems administrator who provided the IPs might have made a
mistake, and scanning the wrong company would be a disaster. The
contract signed with Avatar Online may act as a get-out-of-jail-free
card for penetrating their networks, but will not help if Felix
accidentally roots another company's server! The command he uses
and an excerpt of the results are shown in Example 1.1.
Reading over the results, Felix finds that all of the machines with
reverse-DNS entries resolve to Avatar Online. No other businesses
seem to share the IP space. Moreover, these results give Felix a
rough idea of how many machines are in use and a good idea of
what many are used for. He is now ready to get a bit more intrusive
and try a port scan. He uses Nmap features that try to determine
the application and version number of each service listening on the
network. He also requests that Nmap try to guess the remote
operating system via a series of low-level TCP/IP probes known as
OS fingerprinting. This sort of scan is not at all stealthy, but that
does not concern Felix. He is interested in whether the
administrators of AO even notice these blatant scans. After a bit of
consideration, Felix settles on the following command:
-sS
-p-
-A
-T4
-oA avatartcpscan-121503
6.209.24.0/24 6.207.0.0/22
Felix then looks at every port line in turn. The first port is Secure
Shell (OpenSSH). Version 3.7.1p2 is common, as many
administrators upgraded to this version due to potentially
exploitable buffer management bugs affecting previous versions.
Nmap also notes that the SSH protocol is 1.99, suggesting that the
inferior legacy SSHv1 protocol is supported. A truly paranoid
sysadmin would only allow SSH connections from certain trusted IP
addresses, but one can argue for open access in case the
administrator needs emergency access while far from home.
Security often involves trade-offs, and this one may be justifiable.
Felix makes a note to try his brute force password cracker and
especially his private timing-based SSH user enumeration tool
against the server.
Felix also notes port 53. It is running ISC BIND, which has a long
history of remotely exploitable security holes. Visit the BIND security
page for further details. BIND 9.2.1 even has a potentially
exploitable buffer overflow, although the default build is not
vulnerable. Felix checks and finds that this server is not vulnerable
to the libbind issue, but that is beside the point. This server almost
certainly should not be running an externally-accessible
nameserver. A firewall should only run the bare essentials to
minimize the risk of a disastrous compromise. Besides, this server is
not authoritative for any domains—the real nameservers are on the
production network. An administrator probably only meant for
clients within the firewall to contact this nameserver, but did not
bother locking it down to only the internal interface. Felix will later
try to gather important information from this unnecessary server
using zone transfer requests and intrusive queries. He may attempt
cache poisoning as well. By spoofing the IP of
windowsupdate.microsoft.com or another important download
server, Felix may be able to trick unsuspecting internal client users
into running a trojan-horse program that provides him with full
network access behind the firewall.
The next two open ports are 110 (POP3) and 143 (IMAP). Note that
113 (auth) between them is closed instead of open. POP3 and IMAP
are mail retrieval services which, like BIND, have no legitimate place
on this server. They are also a security risk in that they generally
transfer the mail and (even worse) authentication credentials
unencrypted. Users should probably VPN in and check their mail
from an internal server. These ports could also be wrapped in SSL
encryption. Nmap would have then listed the services as ssl/pop3
and ssl/imap. Felix will try his user enumeration and password
guessing attacks on these services, which will probably be much
more effective than against SSH.
The final open port is a Squid proxy. This is another service that may
have been intended for internal client use and should not be
accessible from the outside (and particularly not on the firewall).
Felix's initially positive opinion of the AO security administrators
drops further. Felix will test whether he can abuse this proxy to
connect to other sites on the Internet. Spammers and malicious
hackers often use proxies in this way to hide their tracks. Even more
critical, Felix will try to proxy his way into the internal network. This
common attack is how Adrian Lamo broke into the New York Times
internal network in 2002. Lamo was caught after he called reporters
to brag about his exploits against the NY Times and other
companies in detail.
The following lines disclose that this is a Linux box, which is valuable
information when attempting exploitation. The low three-day uptime
was detected during OS fingerprinting by sending several probes for
the TCP timestamp option value and extrapolating the line back to
zero.
Trinity fights her way to the computer room and sits down at a
terminal. She quickly determines that the network is using the
private 10.0.0.0/8 network address space. A ping to the network
address generates responses from dozens of machines. An Nmap
ping scan would have provided a more comprehensive list of
available machines, but using the broadcast technique saved
precious seconds. Then she whips out Nmap[6]. The terminal has
version 2.54BETA25 installed. This version is ancient (2001) and less
efficient than newer releases, but Trinity had no time to install a
better version from the future. This job will not take long anyway.
She runs the command nmap -v -sS -O 10.2.1.3. This executes a
TCP SYN scan and OS detection against 10.2.1.3 and provides
verbose output. The host appears to be a security disaster—AIX 3.2
with well over a dozen ports open. Unfortunately, this is not the
machine she needs to compromise. So she runs the same command
against 10.2.2.2. This time the target OS is unrecognized (she
should have upgraded Nmap!) and only has port 22 open. This is the
Secure Shell encrypted administration service. As any sexy PVC-clad
hacker goddess knows, many SSH servers from around that time
(2001) have an exploitable vulnerability in the CRC32 compensation
attack detector. Trinity whips out an all-assembly-code exploit and
utilizes it to change the root password of the target box to
Z10N0101. Trinity uses much more secure passwords under normal
circumstances. She logs in as root and issues a command to disable
the emergency backup power system for 27 city blocks, finishing
just in time! Here is a shot of the action—squint just right and you
should be able to read the text.
MadHat in Wonderland
This story differs from the previous ones in that it is actually true.
Written by frequent Nmap user and contributor Lee “MadHat”
Heath, it describes how he enhanced and customized Nmap for daily
use in a large enterprise. In true open source spirit, he has released
these valuable scripts on his Web site. IP addresses have been
changed to protect the corporate identity. The remainder of this
section is in his own words.
The first issue to come up was speed. Our networks are located
worldwide, yet I was provided with only a single U.S.-based host to
do the scanning. In many cases, firewalls between the sites slowed
the scanning down significantly. Scanning all 100,000 hosts took
over 30 hours, which is unacceptable for a daily scan. So I wrote a
script called nmap-wrapper which runs dozens of Nmap processes in
parallel, reducing the scan time to fifteen hours, even including OS
detection.
The next problem was dealing with so much data. A SQL database
seemed like the best approach for scalability and data-mining
reasons, but I had to abandon that idea due to time pressures. A
future version may add this support. Instead, I used a flat file to
store the results of each class C address range for each day. The
most powerful and extensible way to parse and store this
information was the Nmap XML format, but I chose the “grepable” (-
oG option) format because it is so easy to parse from simple scripts.
Per-host timestamps are also stored for reporting purposes. These
have proven quite helpful when administrators try to blame machine
or service crashes on the scanner. They cannot credibly claim a
service crash at 7:12AM when I have proof that the scan ran at
9:45AM.
10.12.4.8 (ftp-box.foocompany.biz)
21/tcp open ftp
80/tcp open http
443/tcp open https
1027/tcp open IIS
+ 1029/tcp open ms-lsa
38292/tcp open landesk-cba
OS: Microsoft Windows Millennium Edition (Me)
Windows 2000 Professional or Advanced Server
or Windows XP
10.16.234.3 (media.foocompany.biz)
80/tcp open http
+ 554/tcp open rtsp
+ 7070/tcp open realserver
192.168.10.186 (testbox.foocompany.biz)
+ 8082/tcp open blackice-alerts
OS: Linux Kernel 2.4.0 - 2.5.20
172.24.12.58 (mtafoocompany.biz)
+ 25/tcp open smtp
OS: FreeBSD 4.3 - 4.4PRERELEASE
172.23.76.22 (media2.foocorp.biz)
80/tcp open http
1027/tcp open IIS
+ 1040/tcp open netsaint
1755/tcp open wms
3372/tcp open msdtc
6666/tcp open irc-serv
7007/tcp open afs3-bos
OS: Microsoft Windows Millennium Edition (Me)
Windows 2000 Professional or Advanced Server
or Windows XP
192.168.12.56 (ftp2.foocorp.biz)
21/tcp open ftp NcFTPd
192.168.13.130 (dropbox.foocorp.biz)
21/tcp open ftp WU-FTPD 6.00LS
While being far from perfect, these scripts have proven themselves
quite valuable at monitoring large networks for security-impacting
changes. Since Nmap itself is open source, it only seemed fair to
release my scripts to the public as well. I have made them freely
available at http://www.unspecific.com/nmap.
started the session. It is unclear at what point she died and left the
remaining tasks to Trinity.
Legal Issues
When used properly, Nmap helps protect your network from
invaders. But when used improperly, Nmap can (in rare cases) get
you sued, fired, expelled, jailed, or banned by your ISP. Reduce your
risk by reading this legal guide before launching Nmap.
While I agree with the sentiment that port scanning should not be
illegal, it is rarely wise to take legal advice from a T-shirt. Indeed,
taking it from a software engineer and author is only slightly better.
Speak to a competent lawyer within your jurisdiction for a better
understanding of how the law applies to your particular situation.
With that important disclaimer out of the way, here is some general
information that may prove helpful.
While civil and (especially) criminal court cases are the nightmare
scenario for Nmap users, these are very rare. After all, no United
States federal laws explicitly make port scanning illegal. A much
more frequent occurrence is that the target network will notice a
scan and send a complaint to the network service provider where
the scan initiated (your ISP). Most network administrators do not
seem to care or notice the many scans bouncing off their networks
daily, but a few complain. The scan source ISP may track down the
user corresponding to the reported IP address and time, then chide
the user or even kick them off the service. Port scanning without
authorization is sometimes against the provider's acceptable use
policy (AUP). For example, the AUP for the huge cable-modem ISP
Comcast says:
The civil case against Scott was dismissed before trial, implying a
complete lack of merit. The ruling made many Nmap users smile:
Eventually, the criminal court came to the same conclusion and all
charges were dropped. While Scott was vindicated in the end, he
suffered six-figure legal bills and endured stressful years battling
through the court system. The silver lining is that after spending so
much time educating his lawyers about the technical issues
involved, Scott started a successful forensics services company.
While the Moulton case sets a good example (if not legal precedent),
different courts or situations could still lead to worse outcomes.
Remember that many states have their own computer abuse laws,
some of which can arguably make even pinging a remote machine
without authorization illegal[9].
Also remember that ancillary and subsequent actions are often used
as evidence of intent. A port scan by itself does not always signify
an attack. A port scan followed closely by an IIS exploit, however,
broadcasts the intention loud and clear. This is important because
decisions to prosecute (or fire, expel, complain, etc.) are often based
on the whole event and not just one component (such as a port
scan).
Computer/Networks?
Nmap Copyright
While Nmap is open source, it still has a copyright license that must
be respected. As free software, Nmap also carries no warranty.
These issues are covered in much greater detail in the section called
“Legal Notices”. Companies wishing to bundle and use Nmap within
proprietary software and appliances are especially encouraged to
read this section so they don't inadvertently violate the Nmap
license. Fortunately the Nmap Project sells commercial redistribution
licenses for companies which need one.
[7]
These are from the now-defunct AmericanSushi.Com.
The Compast AUP was improved after this was first published. The
[8]
available at http://grove.ufl.edu/~techlaw/vol6/issue1/preston.html.
He has also written an excellent paper relating to the legal risks of
publishing security information and exploits at
http://www.mcandl.com/computer-security.html.
While the 10-year plan is up in the air, the coming year is easier to
predict. As exciting as big new features are, they won't be a focus.
None of us want to see Nmap get bloated and disorganized. So this
will be a year of consolidation. The Zenmap and NSE systems are
not as mature as the rest of Nmap, so improving these is a big
priority. New NSE scripts are great because they extend Nmap's
functionality without the stability risks of incorporating new source
code into Nmap proper. Meanwhile, Zenmap needs usability and
stability improvements, as well as better results visualization.
Another focus is the Nmap web site, which will become more useful
and dynamic. A web discussion system, Nmap demo site, and wiki
are planned.
Nmap may also grow in its ability to handle web scanning. When
Nmap was first developed, different services were often provided as
separate daemons identified by the port number they listen on.
Now, many new services simply run over HTTP and are identified by
a URL path name rather than port number. Scanning for known URL
paths is similar in many ways to port scanning (and to the SunRPC
scanning which Nmap has also done for many years). Nmap already
does some web scanning using the Nmap Scripting Engine (see
Chapter 9, Nmap Scripting Engine), but it would be faster and more
efficient if basic support was built into Nmap itself.
Introduction
Testing Whether Nmap is Already Installed
Command-line and Graphical Interfaces
Downloading Nmap
Verifying the Integrity of Nmap Downloads
Obtaining Nmap from the Subversion (SVN) Repository
Unix Compilation and Installation from Source Code
Configure Directives
If You Encounter Compilation Problems
Linux Distributions
RPM-based Distributions (Red Hat, Mandrake, SUSE, Fedora)
Updating Red Hat, Fedora, Mandrake, and Yellow Dog Linux with Yum
Debian Linux and Derivatives such as Ubuntu
Other Linux Distributions
Windows
Windows 2000 Dependencies
Windows Self-installer
Command-line Zip Binaries
Installing the Nmap zip binaries
Compile from Source Code
Executing Nmap on Windows
Sun Solaris
Apple Mac OS X
Executable Installer
Compile from Source Code
Compile Nmap from source code
Compile Zenmap from source code
Third-party Packages
Executing Nmap on Mac OS X
FreeBSD / OpenBSD / NetBSD
OpenBSD Binary Packages and Source Ports Instructions
FreeBSD Binary Package and Source Ports Instructions
Installation of the binary package
Installation using the source ports tree
NetBSD Binary Package Instructions
Amiga, HP-UX, IRIX, and Other Platforms
Removing Nmap
Introduction
Nmap can often be installed or upgraded with a single command, so
don't let the length of this chapter scare you. Most readers will use
the table of contents to skip directly to sections that concern them.
This chapter describes how to install Nmap on many platforms,
including both source code compilation and binary installation
methods. Graphical and command-line versions of Nmap are
described and contrasted. Nmap removal instructions are also
provided in case you change your mind.
felix~>nmap --version
If Nmap does not exist on the system (or if your PATH is incorrectly
set), an error message such as nmap: Command not found is
reported. As the example above shows, Nmap responds to the
command by printing its version number (here 4.76).
Downloading Nmap
Nmap releases are signed with a special Nmap Project Signing Key,
which can be obtained from the major keyservers or
http://nmap.org/data/nmap_gpgkeys.txt. My key is included in that
file too. The keys can be imported with the command gpg --import
nmap_gpgkeys.txt. You only need to do this once, then you can
verify all future Nmap releases from that machine. Before trusting
the keys, verify that the fingerprints match the values shown in
Example 2.2.
With the proper PGP key in your keyring and the detached signature
file downloaded, verifying an Nmap release takes a single GPG
command, as shown in Example 2.3. That example assumes that
the verified file can be found in the same directory by simply
removing “.asc” from the signature filename. When that isn't the
case, simply pass the target filename as the final argument to GPG.
If the file has been tampered with, the results will look like
Example 2.4.
Repository
While most users only follow the /nmap directory in svn (which pulls
in /nbase, /nsock, and /zenmap on its own), there is one other
interesting directory: /nmap-exp. This directory contains
experimental Nmap branches which Nmap developers create when
they wish to try new things without destabilizing Nmap proper.
When developers feel that an experimental branch is ready for
wider-scale testing, they will generally email the location to the
nmap-dev mailing list.
Once Nmap is checked out, you can build it from source code just as
you would with the Nmap tarball (described later in this chapter).
flog~/nmap> ./configure
checking build system type... x86_64-unknown-linux-
gnu
[hundreds of lines cut]
configure: creating ./config.status
config.status: creating Makefile
config.status: creating nsock_config.h
config.status: nsock_config.h is unchanged
( ) /\ _ (
\ | ( \ ( \.( )
_____
\ \ \ ` ` ) \ ( ___
/ _ \
(_` \+ . x ( .\ \/
\____-----------/ (o) \_
- .- \+ ; ( O
\____
) \_____________ `
\ /
(__ +- .( -'.- <. - _ VVVVVVV VV V\
\/
(_____ ._._: <_ - <- _ (--
_AAAAAAA__A_/ |
. /./.+- . .- / +-- - .
\______________//_ \_______
(__ ' /x / x _/ (
\___' \ /
, x / ( ' . / . /
| \ /
/ / _/ / +
/ \/
' (__/
/ \
NMAP IS A POWERFUL TOOL -- USE
CAREFULLY AND RESPONSIBLY
Configuration complete. Type make (gmake on some
*BSD machines) to compile.
5. Build Nmap (and the Zenmap GUI if its requirements are met):
make
Most of the Unix build options are controlled by the configure script,
as used in step number four above. There are dozens of command-
line parameters and environmental variables which affect the way
Nmap is built. Run ./configure --help for a huge list with brief
descriptions. These are not applicable to building Nmap on
Windows. Here are the options which are either specific to Nmap or
particularly important:
--prefix=<directoryname>
--without-zenmap
--with-openssl=<directoryname>
--with-libpcap=<directoryname>
--with-libpcre=<directoryname>
--with-libdnet=<directoryname>
Libdnet is an excellent networking library that Nmap uses for
sending raw ethernet frames. The version in the Nmap tree is
heavily modified (particularly the Windows code), so the
default is to use that included version. If you wish to use a
version already installed on your system instead, specify
--with-libdnet=<directoryname>. Nmap then expects the
library files to be in <directoryname>/lib and the include files
to be in <directoryname>/include.
--with-localdirs
Ask nmap-dev
Linux Distributions
Linux is the most popular platform for running Nmap. In one user
survey, 86% said that Linux was at least one of the platforms on
which they run Nmap. The first release of Nmap in 1997 only ran on
Linux.
Fedora)
I build RPM packages for every release of Nmap and post them to
the Nmap download page at http://nmap.org/download.html. I build
two packages: The nmap package contains just the command-line
executable and data files, while the zenmap package contains the
optional Zenmap graphical frontend (see Chapter 12, Zenmap GUI
Users' Guide). The zenmap package requires that the nmap package
be installed first. One down side to installing the RPMs rather than
compiling from source is that the RPMs don't support OpenSSL for
version detection and Nmap Scripting Engine probing of SSL
services.
Installing via RPM is quite easy—it even downloads the package for
you when given the proper URLs. The following example downloads
and installs Nmap 4.68, including the frontend. Of course you should
use the latest version at the download site above instead. Any
existing RPM-installed versions are upgraded. Example 2.8
demonstrates this installation process.
As the filenames above imply, these binary RPMs were created for
normal PCs (x86 architecture). I also distribute x86_64 binaries for
64-bit Linux users. These binaries won't work for the relatively few
Linux users on other platforms such as SPARC, Alpha, or PowerPC.
They also may refuse to install if your library versions are
sufficiently different from what the RPMs were initially built on. One
option in these cases would be to find binary RPMs prepared by your
Linux vendor for your specific distribution. The original install CDs or
DVD are a good place to start. Unfortunately, those may not be
current or available. Another option is to install Nmap from source
code as described previously, though you lose the binary package
maintenance consistency benefits. A third option is to build and
install your own binary RPMs from the source RPMs distributed from
the download page above. Example 2.9 demonstrates this technique
with Nmap 4.68.
The Red Hat, Fedora, Mandrake, and Yellow Dog Linux distributions
have an application named Yum which manages software
installation and updates from central RPM repositories. This makes
software installation and updates trivial. Since distribution-specific
Yum repositories are normally used, you know the software has
already been tested for compatibility with your particular
distribution. Most distributions do maintain Nmap in their Yum
repository, but they don't always keep it up to date. This is
particularly problematic if you (like most people) don't always
quickly update to the latest release of your distribution. If you are
running a two-year old Linux release, Yum will often give you a two-
year-old version of Nmap. Even the latest version of distributions
often take months to update to a new Nmap release. So for the
latest version of Nmap on these systems, try the RPMs we distribute
as described in the previous section. But if our RPMs aren't
compatible with your system or you are in a great hurry, installing
Nmap from Yum is usually as simple as executing yum install
nmap (run yum install nmap zenmap if you would like the GUI
too, though some distributions don't yet package Zenmap). Yum
takes care of contacting a repository on the Internet, finding the
appropriate package for your architecture, and then installing it
along with any necessary dependencies. This is shown (edited for
brevity) in Example 2.10. You can later perform yum update to
install available updates to Nmap and other packages in the
repository.
Transaction Summary
=========================================================
====================
Install 1 Package(s)
Update 0 Package(s)
Remove 0 Package(s)
There are far too many Linux distributions available to list here, but
even many of the obscure ones include Nmap in their package tree.
If they don't, you can simply compile from source code as described
in the section called “Unix Compilation and Installation from Source
Code”.
Windows
While Nmap was once a Unix-only tool, a Windows version was
released in 2000 and has since become the second most popular
Nmap platform (behind Linux). Because of this popularity and the
fact that many Windows users do not have a compiler, binary
executables are distributed for each major Nmap release. While it
has improved dramatically, the Windows port is not quite as efficient
or stable as on Unix. Here are some known limitations:
• You cannot generally scan your own machine from itself (using
a loopback IP such as 127.0.0.1 or any of its registered IP
addresses). This is a Windows limitation that we haven't yet
worked around. If you really want to do this, use a TCP
connect scan without pinging (-sT -PN) as that uses the high
level socket API rather than sending raw packets.
• Nmap only supports ethernet interfaces (including most
802.11 wireless cards and many VPN clients) for raw packet
scans. Unless you use the -sT -PN options, RAS connections
(such as PPP dialups) and certain VPN clients are not
supported. This support was dropped when Microsoft removed
raw TCP/IP socket support in Windows XP SP2. Now Nmap
must send lower-level ethernet frames instead.
MaxUserPort
TCPTimedWaitDelay
StrictTimeWaitSeqCheck
Note
I would like to thank Ryan Permeh of eEye, Andy Lutomirski, and
Jens Vogt for their hard work on the Nmap Windows port. For
many years, Nmap was a Unix-only tool, and it would likely still
be that way if not for their efforts.
Windows users have three choices for installing Nmap, all of which
are available from the download page at
http://nmap.org/download.html.
Note
Most users prefer installing Nmap with the self-installer discussed
previously.
Most Windows users prefer to use the Nmap binary self-installer, but
compilation from source code is an option, particularly if you plan to
help with Nmap development. Compilation requires Microsoft Visual
C++ 2008, which is part of their commercial Visual Studio suite. Any
of the Visual Studio editions should work, including the free Visual
C++ 2008 Express SP1.
Many people have asked whether Nmap can be compiled with the
gcc/g++ included with Cygwin or other compilers. Some users have
reported success with this, but we don't maintain instructions for
building Nmap under Cygwin.
Nmap releases now include the Zenmap graphical user interface for
Nmap. If you used the Nmap installer and left the Zenmap field
checked, there should be a new Zenmap entry on your desktop and
Start Menu. Click this to get started. Zenmap is fully documented in
Chapter 12, Zenmap GUI Users' Guide. While many users love
Zenmap, others prefer the traditional command-line approach to
executing Nmap. Here are detailed instructions for users who are
unfamiliar with command-line interfaces:
If you execute Nmap frequently, you can add the Nmap directory
(c:\Program Files\Nmap by default) to your command execution
path. The exact place to set this varies by Windows platform. On my
Windows XP box, I do the following:
Sun Solaris
Solaris has long been well-supported by Nmap. Sun even donated a
complete SPARCstation to the project, which is still being used to
test new Nmap builds. For this reason, many Solaris users compile
and install from source code as described in the section called “Unix
Compilation and Installation from Source Code”.
Users who prefer native Solaris packages will be pleased to learn
that Steven Christensen does an excellent job of maintaining Nmap
packages at http://www.sunfreeware.com for all modern Solaris
versions and architectures. Instructions are on his site, and are
generally very simple: download the appropriate Nmap package for
your version of Solaris, decompress it, and then run pkgadd -d
<packagename>. As is generally the case with contributed binary
packages, these Solaris packages are simple and quick to install.
The advantages of compiling from source are that a newer version
may be available and you have more flexibility in the build process.
Apple Mac OS X
Thanks to several people graciously donating shell accounts on their
Mac OS X boxes, Nmap usually compiles on that platform without
problems. Because not everyone has the development tools
necessary to compile from source, there is an executable installer as
well. Nmap is also available through systems such as MacPorts and
Fink which package Unix software for Mac OS X.
Executable Installer
These exact steps may change, but it is hoped that this general
approach will continue to work.
Third-party Packages
To install using Fink, run the command fink install nmap. Nmap
will be installed as /sw/bin/nmap. To uninstall use the command fink
remove nmap.
To install using MacPorts, run sudo port install nmap. Nmap will
be installed as /opt/local/bin/nmap. To uninstall, run sudo port
uninstall nmap.
These systems install the nmap executable outside the global PATH.
To enable Zenmap to find it, set the nmap_command_path variable
in zenmap.conf to /sw/bin/nmap or /opt/local/bin/nmap as described
in the section called “The nmap Executable”.
Instructions
Instructions
1. The ports tree is often installed with the system itself (usually
in /usr/ports). If you do not already have it, specific installation
instructions are provided in the FreeBSD Handbook chapter
referenced above.
2. As root, execute the following command (replace /usr/ports
with your local ports directory if it differs):
Removing Nmap
If your purpose for removing Nmap is simply to upgrade to the latest
version, you can usually use the upgrade option provided by most
binary package managers. Similarly, installing the latest source
code (as described in the section called “Unix Compilation and
Installation from Source Code”) generally overwrites any previous
from-source installations. Removing Nmap is a good idea if you are
changing install methods (such as from source to RPM or vice versa)
or if you are not using Nmap anymore and you care about the few
megabytes of disk space it consumes.
If you installed Nmap from the Windows installer, simply open the
Control Panel, select “Add or Remove Programs” and select the
“Remove” button for Nmap. You can also remove WinPcap unless
you need it for other applications such as Wireshark.
# cd /usr/local
# rm -f bin/nmap bin/nmapfe bin/xnmap
# rm -f man/man1/nmap.1 man/man1/zenmap.1
# rm -rf share/nmap
# ./bin/uninstall_zenmap
DNS Resolution
Adaptive Retransmission
In 1998, security researcher Antirez (who also wrote the hping2 tool
frequently used in this book) posted to the Bugtraq mailing list an
ingenious new port scanning technique. Idle scan, as it has become
known, allows for completely blind port scanning. Attackers can
actually scan a target without sending a single packet to the target
from their own IP address! Instead, a clever side-channel attack
allows for the scan to be bounced off a dumb “zombie host”.
Intrusion detection system (IDS) reports will finger the innocent
zombie as the attacker. Besides being extraordinarily stealthy, this
scan type permits discovery of IP-based trust relationships between
machines.
While identifying a suitable zombie takes some initial work, you can
keep re-using the good ones.
From the scan above, we learn that the RIAA is not very security
conscious (note the open PC Anywhere, portmapper, and Legato
nsrexec ports). Since they apparently have no firewall, it is unlikely
that they have an IDS. But if they do, it will show kiosk.adobe.com
as the scan culprit. The -PN option prevents Nmap from sending an
initial ping packet to the RIAA machine. That would have disclosed
Ereet's true address. The scan took a long time because -p- was
specified to scan all 65K ports. Don't try to use kiosk for your scans,
as it has already been removed.
By default, Nmap forges probes to the target from the source port
80 of the zombie. You can choose a different port by appending a
colon and port number to the zombie name (e.g. -sI
kiosk.adobe.com:113). The chosen port must not be filtered from
the attacker or the target. A SYN scan of the zombie should show
the port in the open or closed state.
While the section called “Idle Scan Step by Step” describes idle scan
at the fundamental level, the Nmap implementation is far more
complex. Key differences are parallelism for quick execution and
redundancy to reduce false positives.
Parallelizing idle scan is trickier than with other scan techniques due
to indirect method of deducing port states. If Nmap sends probes to
many ports on the target and then checks the new IP ID value of the
zombie, the number of IP ID increments will expose how many
target ports are open, but not which ones. This isn't actually a major
problem, as the vast majority of ports in a large scan will be closed|
filtered. Since only open ports cause the IP ID value to increment,
Nmap will see no intervening increments and can mark the whole
group of ports as closed|filtered. Nmap can scan groups of up to 100
ports in parallel. If Nmap probes a group then finds that the zombie
IP ID has increased <N> times, there must be <N> open ports
among that group. Nmap then finds the open ports with a binary
search. It splits the group into two and separately sends probes to
each. If a subgroup shows zero open ports, that group's ports are all
marked closed|filtered. If a subgroup shows one or more open ports,
it is divided again and the process continues until those ports are
identified. While this technique adds complexity, it can reduce scan
times by an order of magnitude over scanning just one port at a
time.
The four spoofed packets coupled with the probe from Attacker
caused the Zombie to increase its IP ID from 15674 to 15679.
Perfect! Now the real scanning begins. Remember that 15679 is the
latest Zombie IP ID.
Nmap probes ports 20-23. Then it probes Zombie and finds that the
new IP ID is 15680, only one higher than the previous value of
15679. There were no IP ID increments in between those two known
packets, meaning ports 20-23 are probably closed|filtered. It is also
possible that a SYN/ACK from a Target port has simply not arrived
yet. In that case, Zombie has not responded with a RST and thus its
IP ID has not incremented. To ensure accuracy, Nmap will try these
ports again later.
Nmap probes ports 24, 25, and 110 then queries the Zombie IP ID. It
has jumped from 15681 to 15684. It skipped 15682 and 15683,
meaning that two of those three ports are likely open. Nmap cannot
tell which two are open, and it could also be a false positive. So
Nmap drills down deeper, dividing the scan into subgroups.
The first subgroup is ports 24 and 25. The IP ID jumps from 15685 to
15687, meaning that one of these two ports is most likely open.
Nmap tries the divide and conquer approach again, probing each
port separately.
A port 24 probe shows no jump in the IP ID. So that port is not open.
From the results so far, Nmap has tentatively determined:
Stare at this puzzle long enough and you'll find only one solution:
ports 25 and 110 are open while the other five are closed|filtered.
Using this logic, Nmap could cease scanning and print results now. It
used to do so, but that produced too many false positive open ports
when the Zombie wasn't truly idle. So Nmap continues scanning to
verify its results:
Probes of ports 25 and 110 show that they are open, as we deduced
previously.
Introduction
Usage and Examples
Technique Described
Cheats and Fallbacks
Probe Selection and Rarity
Technique Demonstrated
Post-processors
Nmap Scripting Engine Integration
RPC Grinding
SSL Post-processor Notes
nmap-service-probes File Format
Exclude Directive
Probe Directive
match Directive
softmatch Directive
ports and sslports Directives
totalwaitms Directive
rarity Directive
fallback Directive
Putting It All Together
Community Contributions
Submit Service Fingerprints
Submit Database Corrections
Submit New Probes
SOLUTION: Hack Version Detection to Suit Custom Needs, such as Open Proxy Detection
SOLUTION: Find All Servers Running an Insecure or Nonstandard Application Version
Introduction
While Nmap does many things, its most fundamental feature is port
scanning. Point Nmap at a remote machine, and it might tell you
that ports 25/tcp, 80/tcp, and 53/udp are open. Using its nmap-
services database of more than 2,200 well-known services, Nmap
would report that those ports probably correspond to a mail server
(SMTP), web server (HTTP), and name server (DNS) respectively.
This lookup is usually accurate—the vast majority of daemons
listening on TCP port 25 are, in fact, mail servers. However, you
should not bet your security on this! People can and do run services
on strange ports. Perhaps their main web server was already on port
80, so they picked a different port for a staging or test server.
Maybe they think hiding a vulnerable service on some obscure port
prevents “evil hackers” from finding it. Even more common lately is
that people choose ports based not on the service they want to run,
but on what gets through the firewall. When ISPs blocked port 80
after major Microsoft IIS worms CodeRed and Nimda, hordes of users
responded by moving their personal web servers to another port.
When companies block Telnet access due to its horrific security
risks, I have seen users simply run telnetd on the Secure Shell (SSH)
port instead.
Another good reason for determining the service types and version
numbers is that many services share the same port number. For
example, port 258/tcp is used by both the Checkpoint Firewall-1 GUI
management interface and the yak Windows chat client. This makes
a guess based on the nmap-services table even less accurate.
Anyone who has done much scanning knows that you also often find
services listening on unregistered ports—these are a complete
mystery without version detection. A final problem is that filtered
UDP ports often look the same to a simple port scanner as open
ports. But if they respond to the service-specific probes sent by
Nmap version detection, you know for sure that they are open (and
often exactly what is running).
Two more fields that version detection can discover are operating
system and device type. These are also reported on the Service Info
line. We use two techniques here. One is application exclusivity. If
we identify a service as Microsoft Exchange, we know the operating
system is Windows since Exchange doesn't run on anything else.
The other technique is to persuade more portable applications to
divulge the platform information. Many servers (especially web
servers) require very little coaxing. This type of OS detection is
intended to complement Nmap's OS detection system (-O) and can
sometimes report differing results. Consider a Microsoft Exchange
server hidden behind a port-forwarding Unix firewall.
The Nmap version scanning subsystem obtains all of this data by
connecting to open ports and interrogating them for further
information using probes that the specific services understand. This
allows Nmap to give a detailed assessment of what is really running,
rather than just what port numbers are open. Example 7.1 shows
the actual output.
You can see here the way RPC services are treated, with the brute-
force RPC scanner being used to determine that port 111 is rpcbind
version 2. You may also notice that port 515 gives the service as
printer, but that version column is empty. Nmap determined the
service name by probing, but was not able to determine anything
else. On the other hand, port 953 gives the service as “rndc?”. The
question mark tells us that Nmap was not even able to determine
the service name through probing. As a fallback, rndc is mentioned
because that has port 953 registered in nmap-services.
Unfortunately, none of Nmap's probes elicited any sort of response
from rndc. If they had, Nmap would have printed a service
fingerprint and a submission URL so that it could be recognized in
the next version. As it is, Nmap requires a special probe. One might
even be available by the time you read this. the section called
“Community Contributions” provides details on writing your own
probes.
Technique Described
Nmap version scanning is actually rather straightforward. It was
designed to be as simple as possible while still being scalable, fast,
and accurate. The truly nitty-gritty details are best discovered by
downloading and reviewing the source code, but a synopsis of the
techniques used follows.
Nmap first does a port scan as per your instructions, and then
passes all the open or open|filtered TCP and/or UDP ports to the
service scanning module. Those ports are then interrogated in
parallel, although a single port is described here for simplicity.
Nmap reads this data from the socket and finds that no regular
expressions from the Help probe match the data returned. This is
because Nmap normally expects to receive the ESMTP banner
during the NULL probe and match it there.
Because all of Nmap's probes (other than the NULL probe) have a
rarity value associated with them, it is relatively easy to control how
many of them are tried when performing a version scan. Simply
choose an intensity level appropriate for a scan. The higher an
intensity level, the more probes will be tried. So if a very
comprehensive scan is desired, a high intensity level is appropriate
—even though it may take longer than a scan conducted at a lower
intensity level. Nmap's default intensity level is 7 but Nmap provides
the following switches for different scanning needs:
--version-light
--version-all
Technique Demonstrated
If the English description above is not clear enough, you can see for
yourself how it works by adding the --version-trace (and usually -d
(debugging)) options to your Nmap command line. This shows all
the connection and data read/write activity of the service scan. An
annotated real-world example follows.
The DNS server on port 53 does not return anything at all. The first
probe registered to port 53 in nmap-service-probes is
DNSVersionBindReq, which queries a DNS server for its version
number. This is sent onto the wire.
The port 80 NULL probe also failed to return any data. An HTTP GET
request is sent, since that probe is registered to port 80.
Port 25 gives a very helpful response to the Help probe. Other SMTP
servers such as Postfix, Courier, and Exim can often be identified by
this probe as well. If the response did not match, Nmap would have
given up on this service because it had already softmatched smtp
and there are no more SMTP probes in nmap-service-probes.
This service scan run went pretty well. No service required more
than one connection. It took five seconds because Qmail and
Apache hit the five-second NULL probe timeout before Nmap sent
the first real probes. Here is the reward for these efforts:
Post-processors
Nmap is usually finished working on a port once it has deduced the
service and version information as demonstrated above. However,
there are certain services for which Nmap performs additional work.
The post-processors presently available are Nmap Scripting Engine
integration, RPC grinding, and SSL tunneling. Windows SMB
interrogation is under consideration.
1. The TCP and/or UDP port scan finds all of the open ports.
2. Version detection determines which of the open ports use the
SunRPC protocol.
3. The RPC brute force engine determines the program identity
of each RPC port by trying a null command against each of the
600 programs numbers in nmap-rpc. Most of the time Nmap
guesses wrong and receives an error message stating that the
requested program number is not listening on the port. Nmap
continues trying each number in its list until success is
returned for one of them. Nmap gives up in the unlikely event
that it exhausts all of its known program numbers or if the
port sends malformed responses that suggest it is not really
RPC.
Note that the version information is the same for each of the two
open ports, but the service is http on port 80 and ssl/http on port
443. The common case of HTTPS on port 443 is not hard-coded—
Nmap should be able to detect SSL on any port and determine the
underlying protocol for any service that Nmap can detect in clear-
text. If Nmap had not detected the server listening behind SSL, the
service listed would be ssl/unknown. If Nmap had not been built with
SSL support, the service listed would have simply been ssl. The
version column would be blank in both of these cases.
The SSL support for Nmap depends on the free OpenSSL library. It is
not included in the Linux RPM binaries, to avoid breaking systems
which lack these libraries. The Nmap source code distribution
attempts to detect OpenSSL on a system and link to it when
available. See Chapter 2, Obtaining, Compiling, Installing, and
Removing Nmap for details on customizing the build process to
include or exclude OpenSSL.
Exclude Directive
Exclude 53,T:9100,U:30000-40000
This directive excludes the specified ports from the version scan. It
can only be used once and should be near the top of the file, above
any Probe directives. The Exclude directive uses the same format as
the Nmap -p switch, so ranges and comma separated lists of ports
are supported. In the nmap-service-probes included with Nmap the
only ports excluded are TCP port 9100 through 9107. These are
common ports for printers to listen on and they often print any data
sent to them. So a version detection scan can cause them to print
many pages full of probes that Nmap sends, such as SunRPC
requests, help statements, and X11 probes.
Probe Directive
Examples:
<protocol>
This must be either TCP or UDP. Nmap only uses probes that
match the protocol of the service it is trying to scan.
<probename>
This is a plain English name for the probe. It is used in service
fingerprints to describe which probes elicited responses.
<probestring>
match Directive
Examples:
<service>
<pattern>
<versioninfo>
Any of the six fields can be omitted. In fact, all of the fields
can be omitted if no further information on the service is
available. Any of the version fields can include numbered
strings such as $1 or $2, which are replaced (in a Perl-like
fashion) with the corresponding parenthesized substring in the
<pattern>.
softmatch Directive
Examples:
Examples:
ports 21,43,110,113,199,505,540,1248,5432,30444
ports 111,4045,32750-32810,38978
This line tells Nmap what ports the services identified by this probe
are commonly found on. It should only be used once within each
Probe section. The syntax is a slightly simplified version of that
taken by the Nmap -p option. See the examples above. More details
on how this works are in the section called “Technique Described”.
Example:
sslports 443
totalwaitms Directive
Example:
totalwaitms 5000
rarity Directive
Example:
rarity 6
Example:
fallback GetRequest,GenericLines
Community Contributions
No matter how technically advanced a service detection framework
is, it would be nearly useless without a comprehensive database of
services against which to match. This is where the open source
nature of Nmap really shines. The Insecure.Org lab is pretty
substantial by geek standards, but it can never hope to run more
than a tiny percentage of machine types and services that are out
there. Fortunately experience with OS detection fingerprints has
shown that Nmap users together run all of the common stuff, plus a
staggering array of bizarre equipment as well. The Nmap OS
fingerprint database contains more than a thousand entries,
including all sorts of switches, WAPs, VoIP phones, game consoles,
Unix boxes, Windows hosts, printers, routers, PDAs, firewalls, etc.
Version detection also supports user submissions. Nmap users have
contributed thousands of services. There are three primary ways
that the Nmap community helps to make this an exceptional
database: submitting service fingerprints, database corrections, and
new probes.
SF-Port21-TCP:V=3.40PVT16%D=9/6%Time=3F5A961C
%r(NULL,3F,"220\x20stage\x20F
SF:TP\x20server\x20\(Version\x202\.1WU\(1\)\+SCO-
2\.6\.1\+-sec\)\x20ready\
SF:.\r\n")
%r(GenericLines,81,"220\x20stage\x20FTP\x20server\x20\
(Version\x
SF:202\.1WU\(1\)\+SCO-2\.6\.1\+-
sec\)\x20ready\.\r\n500\x20'':\x20command\
SF:x20not\x20understood\.\r\n500\x20'':\x20command\x20not
\x20understood\.\
SF:r\n");
If you receive such a fingerprint, and are sure you know what
daemon version is running on the target host, please submit the
fingerprint at the URL Nmap gives you. The whole submission
process is anonymous (unless you choose to provide identifying
info) and should not take more than a couple minutes. If you are
feeling particularly helpful, scan the system again using -d (Nmap
sometimes gives longer fingerprints that way) and paste both
fingerprints into the fingerprint box on the submission form.
Sometimes people read the file format section and submit their own
working match lines. This is OK, but please submit the service
fingerprint(s) as well because existing scripts make integrating and
testing them relatively easy.
For those who care, the information in the fingerprint above is port
number (21), protocol (TCP), Nmap version (3.40PVT16), date
(September 6), Unix time in hex, and a sequence of probe responses
in the form r({<probename>}, {<responselength>},
"{<responsestring>}").
Generate a fingerprint
Introduction
Reasons for OS Detection
Determining vulnerability of target hosts
Tailoring exploits
Network inventory and support
Detecting unauthorized and dangerous devices
Social engineering
Usage and Examples
TCP/IP Fingerprinting Methods Supported by Nmap
Probes Sent
Sequence generation (SEQ, OPS, WIN, and T1)
ICMP echo (IE)
TCP explicit congestion notification (ECN)
TCP (T2–T7)
UDP (U1)
Response Tests
TCP ISN greatest common divisor (GCD)
TCP ISN counter rate (ISR)
TCP ISN sequence predictability index (SP)
IP ID sequence generation algorithm (TI, CI, II)
Shared IP ID sequence Boolean (SS)
TCP timestamp option algorithm (TS)
TCP options (O, O1–O6)
TCP initial window size (W, W1–W6)
Responsiveness (R)
IP don't fragment bit (DF)
Don't fragment (ICMP) (DFI)
IP initial time-to-live (T)
IP initial time-to-live guess (TG)
Explicit congestion notification (CC)
TCP miscellaneous quirks (Q)
TCP sequence number (S)
TCP acknowledgment number (A)
TCP flags (F)
TCP RST data checksum (RD)
IP total length (IPL)
Unused port unreachable field nonzero (UN)
Returned probe IP total length value (RIPL)
Returned probe IP ID value (RID)
Integrity of returned probe IP checksum value (RIPCK)
Integrity of returned probe UDP checksum (RUCK)
Integrity of returned UDP data (RUD)
ICMP response code (CD)
Fingerprinting Methods Avoided by Nmap
Passive Fingerprinting
Exploit Chronology
Retransmission Times
IP Fragmentation
Open Port Patterns
Retired Tests
Understanding an Nmap Fingerprint
Decoding the Subject Fingerprint Format
Decoding the SCAN line of a subject fingerprint
Decoding the Reference Fingerprint Format
Free-form OS description (Fingerprint line)
Device and OS classification (Class lines)
Test expressions
OS Matching Algorithms
Dealing with Misidentified and Unidentified Hosts
When Nmap Guesses Wrong
When Nmap Fails to Find a Match and Prints a Fingerprint
Modifying the nmap-os-db Database Yourself
Introduction
When exploring a network for security auditing or
inventory/administration, you usually want to know more than the
bare IP addresses of identified machines. Your reaction to
discovering a printer may be very different than to finding a router,
wireless access point, telephone PBX, game console, Windows
desktop, or Unix server. Finer grained detection (such as
distinguishing Mac OS X 10.4 from 10.3) is useful for determining
vulnerability to specific flaws and for tailoring effective exploits for
those vulnerabilities.
OS detection can help reduce these false positives. For example, the
Rwho daemon on unpatched Sun Solaris 7 through 9 may be
remotely exploitable (Sun alert #57659). Remotely determining
vulnerability is difficult, but you can rule it out by finding that a
target system is running Solaris 10.
Tailoring exploits
Social engineering
Another possible use is social engineering. Lets say that you are
scanning a target company and Nmap reports a “Datavoice TxPORT
PRISM 3000 T1 CSU/DSU 6.22/2.06”. You could call up the target
pretending to be Datavoice support and discuss some issues with
their PRISM 3000. Tell them you are about to announce a big
security hole, but are first providing the patch to valued customers.
Some naive administrators might assume that only an authorized
engineer from Datavoice would know so much about their CSU/DSU.
Of course the patch you send them is a Trojan horse that gives you
remote access to sniff and traipse through their network. Be sure to
read the rest of this chapter for detection accuracy and verification
advice before trying this. If you guess the target system wrong and
they call the police, that will be an embarrassing story to tell your
cellmates.
# nmap -O -v scanme.nmap.org
Device type
Running
OS details
Uptime guess
Network Distance
The good news is that hardly anyone uses rlogin anymore, and
many operating systems have been fixed to use unpredictable
initial sequence numbers as proposed by RFC 1948. For these
reasons, this line is only printed in verbose mode. Sadly, many
vendors still ship vulnerable operating systems and devices.
Even the fixed ones often vary in implementation, which
leaves them valuable for OS detection purposes. The class
describes the ISN generation algorithm used by the target,
and difficulty is a rough estimate of how hard the system
makes blind IP spoofing (0 is the easiest). The parenthesized
comment is based on the difficulty index and ranges from
Trivial joke to Easy, Medium, Formidable, Worthy challenge,
and finally Good luck! Further details about sequence tests are
provided in the section called “TCP ISN greatest common
divisor (GCD)”.
IP ID sequence generation
In this example, the line “No exact OS matches for host” means that
TCP/IP fingerprinting failed to find an exact match. Fortunately, the
Service Info field a few lines down discloses that the OS is HP-UX. If
several operating systems were detected (which can happen with
NAT gateway boxes that redirect ports to several different
machines), the field would be OSs and the values would be comma
separated. The Service Info line can also contain hostnames and
device types found during the version scan. The focus of this
chapter is on TCP/IP fingerprinting though, since version detection
was covered in Chapter 7, Service and Application Version
Detection.
Like just about every other part of Nmap, results ultimately come
from the target machine itself. While rare, systems are occasionally
configured to confuse or mislead Nmap. Several programs have
even been developed specifically to trick Nmap OS detection (see
the section called “OS Spoofing”). Your best bet is to use numerous
reconnaissance methods to explore a network, and don't trust any
one of them.
The following sections are highly technical and reveal the hidden
workings of Nmap OS detection. Nmap can be used effectively
without understanding this, though the material can help you better
understand remote networks and also detect and explain certain
anomalies. Plus, some of the techniques are pretty cool. Readers in
a hurry may skip to the section called “Dealing with Misidentified
and Unidentified Hosts”. But for those of you who are ready for a
journey through TCP explicit congestion notification, reserved UDP
header bits, initial sequence numbers, bogus flags, and Christmas
tree packets: read on!
Probes Sent
These packets vary in the TCP options they use and the TCP window
field value. The following list provides the options and values for all
six packets. The listed window field values do not reflect window
scaling. EOL is the end-of-options-list option, which many sniffing
tools don't show by default.
The results of these tests include four result category lines. The first,
SEQ, contains results based on sequence analysis of the probe
packets. These test results are GCD, SP, ISR, TI, II, TS, and SS. The
next line, OPS contains the TCP options received for each of the
probes (the test names are O1 through 06). Similarly, the WIN line
contains window sizes for the probe responses (named W1 through
W6). The final line related to these probes, T1, contains various test
values for packet #1. Those results are for the R, DF, T, TG, W, S, A,
F, O, RD, and Q tests. These tests are only reported for the first
probe since they are almost always the same for each probe.
The IE test involves sending two ICMP echo request packets to the
target. The first one has the IP DF bit set, a type-of-service (TOS)
byte value of zero, a code of nine (even though it should be zero),
the sequence number 295, a random IP ID and ICMP request
identifier, and a random character repeated 120 times for the data
payload.
The second ping query is similar, except a TOS of four
(IP_TOS_RELIABILITY) is used, the code is zero, 150 bytes of data is
sent, and the IP ID, request ID, and sequence numbers are
incremented by one from the previous query values.
TCP (T2–T7)
The six T2 through T7 tests each send one TCP probe packet. With
one exception, the TCP options data in each case is (in hex)
03030A0102040109080AFFFFFFFF000000000402. Those 20 bytes
correspond to window scale (10), NOP, MSS (265), Timestamp
(TSval: 0xFFFFFFFF; TSecr: 0), then SACK permitted. The exception
is that T7 uses a Window scale value of 15 rather than 10. The
variable characteristics of each probe are described below:
• T2 sends a TCP null (no flags set) packet with the IP DF bit set
and a window field of 128 to an open port.
• T3 sends a TCP packet with the SYN, FIN, URG, and PSH flags
set and a window field of 256 to an open port. The IP DF bit is
not set.
• T4 sends a TCP ACK packet with IP DF and a window field of
1024 to an open port.
• T5 sends a TCP SYN packet without IP DF and a window field
of 31337 to a closed port.
• T6 sends a TCP ACK packet with IP DF and a window field of
32768 to a closed port.
• T7 sends a TCP packet with the FIN, PSH, and URG flags set
and a window field of 65535 to a closed port. The IP DF bit is
not set.
UDP (U1)
This probe is a UDP packet sent to a closed port. The character ‘C’
(0x43) is repeated 300 times for the data field. The IP ID value is set
to 0x1042 for operating systems which allow us to set this. If the
port is truly closed and there is no firewall in place, Nmap expects to
receive an ICMP port unreachable message in return. That response
is then subjected to the R, DF, T, TG, IPL, UN, RIPL, RID, RIPCK,
RUCK, and RUD tests.
Response Tests
The previous section describes probes sent by Nmap, and this one
completes the puzzle by describing the barrage of tests performed
on responses. The short names (such as DF, R, and RIPCK) are those
used in the nmap-os-db fingerprint database to save space. All
numerical test values are given in hexadecimal notation, without
leading zeros, unless noted otherwise. The tests are documented in
roughly the order they appear in fingerprints.
The SEQ test sends six TCP SYN packets to an open port of the
target machine and collects SYN/ACK packets back. Each of these
SYN/ACK packets contains a 32-bit initial sequence number (ISN).
This test attempts to determine the smallest number by which the
target host increments these values. For example, many hosts
(especially old ones) always increment the ISN in multiples of
64,000.
This value reports the average rate of increase for the returned TCP
initial sequence number. Recall that a difference is taken between
each two consecutive probe responses and stored in the previously
discussed diff1 array. Those differences are each divided by the
amount of time elapsed (in seconds—will generally be about 0.1)
between sending the two probes which generated them. The result
is an array, which we'll call seq_rates containing the rates of ISN
counter increases per second. The array has one element for each
diff1 value. An average is taken of the array values. If that average
is less than one (e.g. a constant ISN is used), ISR is zero. Otherwise
ISR is eight times the binary logarithm (log base-2) of that average
value, rounded to the nearest integer.
While the ISR test measures the average rate of initial sequence
number increments, this value measures the ISN variability. It
roughly estimates how difficult it would be to predict the next ISN
from the known sequence of six probe responses. The calculation
uses the difference array (seq_rates) and GCD values discussed in
the previous section.
This test is only performed if at least four responses were seen. If
the previously computed GCD value is greater than nine, the
elements of the previously computed seq_rates array are divided by
that value. We don't do the division for smaller GCD values because
those are usually caused by chance. A standard deviation of the
array of the resultant values is then taken. If the result is one or
less, SP is zero. Otherwise the binary logarithm of the result is
computed, then it is multiplied by eight, rounded to the nearest
integer, and stored as SP.
Please keep in mind that this test is only done for OS detection
purposes and is not a full-blown audit of the target ISN generator.
There are many algorithm weaknesses that lead to easy
predictability even with a high SP value.
Let avg be the final TCP sequence response IP ID minus the first TCP
sequence response IP ID, divided by the difference in probe
numbers. If probe #1 returns an IP ID of 10,000 and probe #6
returns 20,000, avg would be (20,000 − 10,000) / (6 − 1), which
equals 2,000.
If the first ICMP echo response IP ID is less than the final TCP
sequence response IP ID plus three times avg, the SS result is S.
Otherwise it is O.
While this test is generally named O, the six probes sent for
sequence generation purposes are a special case. Those are
inserted into the special OPS test line and take the names O1
through O6 to distinguish which probe packet they relate to. The “O”
stands for “options”. Despite the different names, each test O1
through O6 is processed exactly the same way as the other O tests.
This test simply records the 16-bit TCP window size of the received
packet. It is quite effective, since there are more than 80 values that
at least one OS is known to send. A down side is that some
operating systems have more than a dozen possible values by
themselves. This leads to false negative results until we collect all of
the possible window sizes used by an operating system.
While this test is generally named W, the six probes sent for
sequence generation purposes are a special case. Those are
inserted into a special WIN test line and take the names W1 through
W6. The window size is recorded for all of the sequence number
probes because they differ in TCP MSS option values, which causes
some operating systems to advertise a different window size.
Despite the different names, each test is processed exactly the
same way.
Responsiveness (R)
This test simply records whether the target responded to a given
probe. Possible values are Y and N. If there is no reply, remaining
fields for the test are omitted.
A risk with this test involves probes that are dropped by a firewall.
This leads to R=N in the subject fingerprint. Yet the reference
fingerprint in nmap-os-db may have R=Y if the target OS usually
replies. Thus the firewall could prevent proper OS detection. To
reduce this problem, reference fingerprints generally omit the R=Y
test from the IE and U1 probes, which are the ones most likely to be
dropped. In addition, if Nmap is missing a closed TCP port for a
target, it will not set R=N for the T5, T6, or T7 tests even if the port
it tries is non-responsive. After all, the lack of a closed port may be
because they are all filtered.
This is simply a modified version of the DF test that is used for the
special IE probes. It compares results of the don't fragment bit for
the two ICMP echo request probes sent. It has four possible values,
which are enumerated in Table 8.2.
Value Description
N Neither of the ping responses have the DF bit set.
S Both responses echo the DF value of the probe.
Y Both of the response DF bits are set.
O The one remaining other combination—both responses have the DF bit toggled.
Even though an eight-bit field like TTL can never hold values greater
than 0xFF, this test occasionally results in values of 0x100 or higher.
This occurs when a system (could be the source, a target, or a
system in between) corrupts or otherwise fails to correctly
decrement the TTL. It can also occur due to asymmetric routes.
Nmap can also learn from the system interface and routing tables
when the hop distance is zero (localhost scan) or one (on the same
network segment). This value is used when Nmap prints the hop
distance for the user, but it is not used for T result computation.
This test is only used for the ECN probe. That probe is a SYN packet
which includes the CWR and ECE congestion control flags. When the
response SYN/ACK is received, those flags are examined to set the
CC (congestion control) test value as described in Table 8.3.
Table 8.3. CC test values
Value Description
Y Only the ECE bit is set (not CWR). This host supports ECN.
N Neither of these two bits is set. The target does not support ECN.
S Both bits are set. The target does not support ECN, but it echoes back what it thinks is a
reserved bit.
O The one remaining combination of these two bits (other).
This tests for two quirks that a few implementations have in their
TCP stack. The first is that the reserved field in the TCP header (right
after the header length) is nonzero. This is particularly likely to
happen in response to the ECN test as that one sets a reserved bit
in the probe. If this is seen in a packet, an “R” is recorded in the Q
string.
The other quirk Nmap tests for is a nonzero urgent pointer field
value when the URG flag is not set. This is also particularly likely to
be seen in response to the ECN probe, which sets a non-zero urgent
field. A “U” is appended to the Q string when this is seen.
This test examines the 32-bit sequence number field in the TCP
header. Rather than record the field value as some other tests do,
this one examines how it compares to the TCP acknowledgment
number from the probe that elicited the response. It then records
the appropriate value as shown in Table 8.4.
Value Description
Z Sequence number is zero.
A Sequence number is the same as the acknowledgment number in the probe.
A+ Sequence number is the same as the acknowledgment number in the probe plus one.
O Sequence number is something else (other).
TCP acknowledgment number (A)
Value Description
Z Acknowledgment number is zero.
S Acknowledgment number is the same as the sequence number in the probe.
S+ Acknowledgment number is the same as the sequence number in the probe plus one.
O Acknowledgment number is something else (other).
This field records the TCP flags in the response. Each letter
represents one flag, and they occur in the same order as in a TCP
packet (from high-bit on the left, to the low ones). So the value SA
represents the SYN and ACK bits set, while the value AS is illegal
(wrong order). The possible flags are shown in Table 8.6.
This test records the total length (in octets) of an IP packet. It is only
used for the port unreachable response elicited by the U1 test. That
length varies by implementation because they are allowed to
choose how much data from the original probe to include, as long as
they meet the minimum RFC 792 requirement. That requirement is
to include the original IP header and at least eight bytes of data.
The code value of an ICMP echo reply (type zero) packet is supposed
to be zero. But some implementations wrongly send other values,
particularly if the echo request has a nonzero code (as one of the IE
tests does). The response code values for the two probes are
combined into a CD value as described in Table 8.7.
Value Description
Z Both code values are zero.
S Both code values are the same as in the corresponding probe.
<N When they both use the same non-zero number, it is shown here.
N>
O Any other combination.
Passive Fingerprinting
Exploit Chronology
Warning
If you use denial of service (DoS) exploits as part of your OS
detection suite, remember to perform those tests last.
Retransmission Times
TCP implementations have significant leeway in exactly how long
they wait before retransmitting packets. The proof-of-concept tools
Ring and Cron-OS are available to exploit this. They send a SYN
packet to an open port, then ignore the SYN/ACK they receive rather
than acknowledging it with an ACK (to complete the connection) or a
RST (to kill it). The target host will resend the SYN/ACK several more
times, and these tools track every subsecond of the wait. While
some information can indeed be gleaned from this technique, there
are several reasons that I haven't incorporated the patch into Nmap:
IP Fragmentation
While this heuristic is often useful, it just isn't reliable enough for
Nmap. Combinations of ports can be obscured by firewall rules, and
most mainstream protocols are available on multiple platforms.
OpenSSH servers can be run on Windows, and the “Windows SMB”
ports can be serviced by Samba running on a Unix machine. Port
forwarding clouds the issue even further. A machine which appears
to be running Microsoft IIS might be a Unix firewall simply
forwarding port 80 to a Windows machine.
For these reasons, Nmap does not consider open port numbers
during TCP/IP stack fingerprinting. However, Nmap can use version
detection information (see Chapter 7, Service and Application
Version Detection) to separately discover operating system and
device type information. By keeping the OS detection results
discovered by OS detection and version detection separate, Nmap
can gracefully handle a Checkpoint firewall which uses TCP port
forwarding to a Windows web server. The stack fingerprinting results
should be “Checkpoint Firewall-1” while version detection should
suggest that the OS is Windows. Keep in mind that only a small
fraction of version detection signatures include OS and device type
information—we can only populate these fields when the application
divulges the information or when it only runs on one OS or device
type.
Retired Tests
There are some tests that were once performed by Nmap, but which
have been retired because they were found not to help in
distinguishing operating systems and only took up space in the
database. Two tests in the IE line were removed: DLI checked the
length of the data payload in returned packets and SI checked the
ICMP sequence numbers. They were never found to vary from the
values sent. In the U1 line, the RUL test checked the length of the
UDP packet returned. It was different from what was sent in only one
case out of more than 1,700. These tests were removed in
March 2009.
OS:SCAN(V=4.85BETA4%D=3/27%OT=22%CT=1%CU=44663%PV=N
%DS=0%G=Y%TM=49CD5E4B%P=
OS:i686-pc-linux-gnu)SEQ(SP=CB%GCD=1%ISR=CD%TI=Z%CI=Z
%II=I%TS=8)OPS(O1=M400
OS:CST11NW5%O2=M400CST11NW5%O3=M400CNNT11NW5%O4=M400CST11
NW5%O5=M400CST11NW
OS:5%O6=M400CST11)WIN(W1=8000%W2=8000%W3=8000%W4=8000%W5=
8000%W6=8000)ECN(R
OS:=Y%DF=Y%T=40%W=8018%O=M400CNNSNW5%CC=N%Q=)T1(R=Y%DF=Y
%T=40%S=O%A=S+%F=AS
OS:%RD=0%Q=)T2(R=N)T3(R=Y%DF=Y%T=40%W=8000%S=O%A=S+%F=AS
%O=M400CST11NW5%RD=
OS:0%Q=)T4(R=Y%DF=Y%T=40%W=0%S=A%A=Z%F=R%O=
%RD=0%Q=)T5(R=Y%DF=Y%T=40%W=0%S=
OS:Z%A=S+%F=AR%O=%RD=0%Q=)T6(R=Y%DF=Y%T=40%W=0%S=A%A=Z
%F=R%O=%RD=0%Q=)T7(R=
OS:Y%DF=Y%T=40%W=0%S=Z%A=S+%F=AR%O=%RD=0%Q=)U1(R=Y%DF=N
%T=40%IPL=164%UN=0%R
OS:IPL=G%RID=G%RIPCK=G%RUCK=G%RUD=G)IE(R=Y%DFI=N
%T=40%CD=S)
SCAN(V=4.85BETA4%D=3/27%OT=22%CT=1%CU=44663%PV=N%DS=0%G=Y
%TM=49CD5E4B%
P=i686-pc-linux-gnu)
SEQ(SP=CB%GCD=1%ISR=CD%TI=Z%CI=Z%II=I%TS=8)
OPS(O1=M400CST11NW5%O2=M400CST11NW5%O3=M400CNNT11NW5%
O4=M400CST11NW5%O5=M400CST11NW5%O6=M400CST11)
WIN(W1=8000%W2=8000%W3=8000%W4=8000%W5=8000%W6=8000)
ECN(R=Y%DF=Y%T=40%W=8018%O=M400CNNSNW5%CC=N%Q=)
T1(R=Y%DF=Y%T=40%S=O%A=S+%F=AS%RD=0%Q=)
T2(R=N)
T3(R=Y%DF=Y%T=40%W=8000%S=O%A=S+%F=AS
%O=M400CST11NW5%RD=0%Q=)
T4(R=Y%DF=Y%T=40%W=0%S=A%A=Z%F=R%O=%RD=0%Q=)
T5(R=Y%DF=Y%T=40%W=0%S=Z%A=S+%F=AR%O=%RD=0%Q=)
T6(R=Y%DF=Y%T=40%W=0%S=A%A=Z%F=R%O=%RD=0%Q=)
T7(R=Y%DF=Y%T=40%W=0%S=Z%A=S+%F=AR%O=%RD=0%Q=)
U1(R=Y%DF=N%T=40%IPL=164%UN=0%RIPL=G%RID=G%RIPCK=G%RUCK=G
%RUD=G)
IE(R=Y%DFI=N%T=40%CD=S)
While this still isn't the world's most intuitive format (we had to keep
it short), the format is much clearer now. Every line is a category,
such as SEQ for the sequence generation tests, T3 for the results
from that particular TCP probe, and IE for tests related to the two
ICMP echo probes.
Just as multiple fingerprints are often needed for one OS, sometimes
a single fingerprint describes several systems. If two systems give
the exact same results for every single test, Nmap has little choice
but to offer up both as possibilities. This commonly occurs for
several reasons. One is that vendors may release a new version of
their OS without any significant changes to their IP stack. Maybe
they made important changes elsewhere in the system, or perhaps
they did little but want to make a bunch of money selling
“upgrades”. In these cases, Nmap often prints a range such as
Apple Mac OS X 10.4.8 - 10.4.11 or Sun Solaris 9 or 10.
There are also cases where numerous vendors private label the
exact same OEM device with their own brand name and model
number. Here again, Nmap must simply list the possibilities. But
distinguishing these is less important because they are all
fundamentally the same device.
Tip
If the description printed by Nmap (which comes from the
Fingerprint line) isn't informative enough for you, more detailed
information may be available in comments above the fingerprint
itself in nmap-os-db. You can find it installed on your system or
look up the latest version at http://nmap.org/data/nmap-os-db.
Search for the exact OS description that Nmap gives you. Keep in
mind that there may be several Fingerprint lines with exactly the
same description, so you may have to examine them all. Or use
the Nmap XML output, which shows the line number of each
match.
Every fingerprint has one or more Class lines. Each contains four
well-defined fields: vendor, OS name, OS family, and device type.
The fields are separated by the pipe symbol (|).
Each field may contain just one value. When a fingerprint represents
more than one possible combination of these four fields, multiple
Class lines are used. Example 8.6 provides some example
Fingerprint lines followed by their corresponding classifications.
Test expressions
OS Matching Algorithms
Nmap's algorithm for detecting matches is relatively simple. It takes
a subject fingerprint and tests it against every single reference
fingerprint in nmap-os-db.
Once all of the probe lines are tested for a fingerprint, Nmap divides
NumMatchPoints by PossiblePoints. The result is a confidence factor
describing the probability that the subject fingerprint matches that
particular reference fingerprint. It is treated as a percentage, so
1.00 is a perfect match while 0.95 is very close.
MatchPoints
SEQ(SP=25%GCD=75%ISR=25%TI=100%CI=50%II=100%SS=80%TS=100)
OPS(O1=20%O2=20%O3=20%O4=20%O5=20%O6=20)
WIN(W1=15%W2=15%W3=15%W4=15%W5=15%W6=15)
ECN(R=100%DF=20%T=15%TG=15%W=15%O=15%CC=100%Q=20)
T1(R=100%DF=20%T=15%TG=15%S=20%A=20%F=30%RD=20%Q=20)
T2(R=80%DF=20%T=15%TG=15%W=25%S=20%A=20%F=30%O=10%RD=20%Q
=20)
T3(R=80%DF=20%T=15%TG=15%W=25%S=20%A=20%F=30%O=10%RD=20%Q
=20)
T4(R=100%DF=20%T=15%TG=15%W=25%S=20%A=20%F=30%O=10%RD=20%
Q=20)
T5(R=100%DF=20%T=15%TG=15%W=25%S=20%A=20%F=30%O=10%RD=20%
Q=20)
T6(R=100%DF=20%T=15%TG=15%W=25%S=20%A=20%F=30%O=10%RD=20%
Q=20)
T7(R=80%DF=20%T=15%TG=15%W=25%S=20%A=20%F=30%O=10%RD=20%Q
=20)
U1(R=50%DF=20%T=15%TG=15%TOS=0%IPL=100%UN=100%RIPL=100%RI
D=100%RIPCK=100%RUCK=100%RUL=100%RUD=100)
IE(R=50%DFI=40%T=15%TG=15%TOSI=0%CD=100%SI=100%DLI=100)
Once all of the reference fingerprints have been evaluated, Nmap
orders them and prints the perfect matches (if there aren't too
many). If there are no perfect matches, but some are very close,
Nmap may print those. Guesses are more likely to be printed if the
--osscan-guess option is given.
Generate a fingerprint
If you have gotten this far and are still able to submit, good for you!
Please submit the information at http://insecure.org/cgi-
bin/submit.cgi?corr-os
Fingerprint
Introduction
Usage and Examples
Script Categories
Command-line Arguments
Script Selection
Arguments to Scripts
Complete Examples
Script Format
description Field
categories Field
author Field
license Field
runlevel Field
Port and Host Rules
Action
Script Language
Lua Base Language
NSE Scripts
NSE Libraries
List of All Libraries
Adding C Modules to Nselib
Nmap API
Information Passed to a Script
Network I/O API
Connect-style network I/O
Raw packet network I/O
Thread Mutexes
Exception Handling
The Registry
Script Writing Tutorial
The Head
The Rule
The Mechanism
Writing Script Documentation (NSEDoc)
NSE Documentation Tags
Version Detection Using NSE
Example Script: finger.nse
Implementation Details
Initialization Phase
Matching Scripts with Targets
Script Execution
Introduction
The Nmap Scripting Engine (NSE) is one of Nmap's most powerful
and flexible features. It allows users to write (and share) simple
scripts to automate a wide variety of networking tasks. Those scripts
are then executed in parallel with the speed and efficiency you
expect from Nmap. Users can rely on the growing and diverse set of
scripts distributed with Nmap, or write their own to meet custom
needs.
Vulnerability detection
Backdoor detection
Vulnerability exploitation
These listed items were our initial goals, and we expect Nmap users
to come up with even more inventive uses for NSE.
NSE is activated with the -sC option (or --script if you wish to specify
a custom set of scripts) and results are integrated into Nmap normal
and XML output. Two types of scripts are supported: service and
host scripts. Service scripts relate to a certain open port (service) on
the target host, and any results they produce are included next to
that port in the Nmap output port table. Host scripts, on the other
hand, run no more than once against each target IP and produce
results below the port table. Example 9.1 shows a typical script
scan. Service scripts producing output in this example are ssh-
hostkey, which provides the system's RSA and DSA SSH keys, and
rpcinfo, which queries portmapper to enumerate available services.
The only host script producing output in this example is smb-os-
discovery, which collects a variety of information from SMB servers.
Nmap discovered all of this information in a third of a second.
Script Categories
NSE scripts define a list of categories they belong to. Currently
defined categories are auth, default, discovery, external, intrusive,
malware, safe, version, and vuln. Category names are not case
sensitive. The following list describes each category.
auth
default
These scripts are the default set and are run when using the
-sC or -A options rather than listing scripts with --script. This
category can also be specified explicitly like any other using
--script=default. Many factors are considered in deciding
whether a script should be run by default:
Speed
Usefulness
Verbosity
Intrusiveness
Privacy
discovery
external
intrusive
malware
safe
version
vuln
Command-line Arguments
-sC
--script <filename>|<category>|<directory>|<expression>|all[,...]
--datadir
$NMAPDIR
~/.nmap (not searched on
Windows)
NMAPDATADIR
the current directory
--script-args <args>
--script-trace
Some other Nmap options have effects on script scans. The most
prominent of these is -sV. A version scan automatically executes the
scripts in the version category. The scripts in this category are
slightly different than other scripts because their output blends in
with the version scan results and they do not produce any script
scan output.
Script Selection
Loads all scripts whose name starts with http-, such as http-
auth.nse and http-open-proxy.nse. The argument to --script
had to be in quotes to protect the wildcard from the shell.
More complicated script selection can be done using the and, or,
and not operators to build Boolean expressions. The operators have
the same precedence as in Lua: not is the highest, followed by and
and then or. You can alter precedence by using parentheses.
Because expressions contain space characters it is necessary to
quote them.
Loads those scripts that are in both the default and safe
categories.
Arguments to Scripts
Arguments may be passed to NSE scripts using the --script-args
option. The arguments describe a table of key-value pairs and
possibly array values. The arguments are provided to scripts as a
table in the registry called nmap.registry.args.
Values may also be tables enclosed in {}, just as in Lua. A table may
contain simple string values, for example a list of proxy hosts; or
more name-value pairs, including nested tables. Nested subtables
are commonly used to pass arguments specific to one script, in a
table named after the script. That is what is happening with the
whois table in the example below.
{user="foo",pass=",
{}=bar",whois={whodb="nofollow+ripe"},userdb="C:\\Some\\P
ath\\To\\File"}
You could then access the username "foo" inside your script with
this statement:
Complete Examples
Script Format
NSE scripts consist of two–five descriptive fields along with either a
port or host rule defining when the script should be executed and an
action block containing the actual script instructions. Values can be
assigned to the descriptive fields just as you would assign any other
Lua variables. Their names must be lowercase as shown in this
section.
description Field
The description field describes what a script is testing for and any
important notes the user should be aware of. Depending on script
complexity, the description may vary from a few sentences to a few
paragraphs. The first paragraph should be a brief synopsis of the
script function suitable for stand-alone presentation to the user.
Further paragraphs may provide much more script detail.
categories Field
The author field contains the script authors' names and contact
information. If you are worried about spam, feel free to omit or
obscure your email address, or give your home page URL instead.
This optional field is not used by NSE, but gives script authors due
credit or blame.
license Field
The Nmap license is similar to the GNU GPL. Script authors may use
a BSD-style license (no advertising clause) instead if they prefer
that.
runlevel Field
Action
Script Language
The core of the Nmap Scripting Engine is an embeddable Lua
interpreter. Lua is a lightweight language designed for extensibility.
It offers a powerful and well documented API for interfacing with
other software such as Nmap.
The second part of the Nmap Scripting Engine is the NSE Library,
which connects Lua and Nmap. This layer handles issues such as
initialization of the Lua interpreter, scheduling of parallel script
execution, script retrieval and more. It is also the heart of the NSE
network I/O framework and the exception handling mechanism. It
also includes utility libraries to make scripts more powerful and
convenient. The utility library modules and extensions are described
in the section called “NSE Libraries”.
Lua Base Language
NSE Scripts
This section (a long list of NSE scripts with brief summaries) is only
provided in the printed edition of this book because we already
provide a better online interface to the information at the NSE
Documentation Portal.
NSE Libraries
In addition to the significant built-in capabilities of Lua, we have
written or integrated many extension libraries which make script
writing more powerful and convenient. These libraries (sometimes
called modules) are compiled if necessary and installed along with
Nmap. They have their own directory, nselib, which is installed in
the configured Nmap data directory. Scripts need only require the
default libraries in order to use them.
base64
bin
bit
comm
datafiles
dns
http
IMAP functions.
ipOps
listop
match
msrpc
By making heavy use of the 'smb' library, this library will call
various MSRPC functions. The functions used here can be
accessed over TCP ports 445 and 139, with an established
session. A NULL session (the default) will work for some
functions and operating systems (or configurations), but not
for others.
msrpcperformance
msrpctypes
netbios
Creates and parses NetBIOS traffic. The primary use for this is
to send NetBIOS name requests.
nmap
nsedebug
openssl
OpenSSL bindings.
packet
pcre
pop3
POP3 functions.
shortport
smb
smbauth
snmp
SNMP functions.
ssh1
Functions for the SSH-1 protocol.
ssh2
stdnse
strbuf
tab
unpwdb
url
This function will now be known as md5 to NSE. Next the library is
registered with a call to luaL_register inside the initialization
function luaopen_openssl, as shown next. Some lines relating to the
registration of OpenSSL BIGNUM types have been omitted:
Nmap API
NSE scripts have access to several Nmap facilities for writing flexible
and elegant scripts. The API provides target host details such as port
states and version detection results. It also offers an interface to the
Nsock library for efficient network I/O.
host
host.os
host.ip
host.targetname
host.directly_connected
host.mac_addr
host.mac_addr_src
Our own MAC address, which was used to connect to the host
(either our network card's, or (with --spoof-mac) the spoofed
address).
host.interface
host.bin_ip
host.bin_ip_src
port
The port table is passed to an NSE service script (i.e. only
those with a portrule rather than a hostrule) in the same
fashion as the host table. It contains information about the
port against which the script is running. While this table is not
passed to host scripts, port states on the target can still be
requested from Nmap using the nmap.get_port_state() call.
port.number
port.protocol
Defines the protocol of the target port. Valid values are "tcp"
and "udp".
port.service
port.version
Name Description
name Contains the service name Nmap decided on for the port.
name_confidence Evaluates how confident Nmap is about the accuracy of
name, from 1 (least confident) to 10.
product, version, These five variables are the same as those described under
extrainfo, hostname, <versioninfo> in the section called “match Directive”.
ostype, devicetype
service_tunnel Contains the string "none" or "ssl" based on whether or
Name Description
not Nmap used SSL tunneling to detect the service.
service_fp The service fingerprint, if any, is provided in this value. This
is described in the section called “Community
Contributions”.
rpc_status Contains a string value of good_prog if we were able to
determine the program number of an RPC service listening
on the port, unknown if the port appears to be RPC but we
couldn't determine the program number, not_rpc if the port
doesn't appear be RPC, or untested if we haven't checked
for RPC status.
rpc_program, The detected RPC program number and the range of version
rpc_lowver, numbers supported by that program. These will be nil if
rpc_highver rpc_status is anything other than good_prog.
port.state
This part of the network API should be suitable for most classical
network uses: Users create a socket, connect it to a remote address,
send and receive data and finally close the socket. Everything up to
the Transport layer (which is either TCP, UDP or SSL) is handled by
the library.
require("nmap")
The pcap_open method creates a handle for raw socket reads from
an ordinary socket object. This method takes a callback function,
which computes a packet hash from a packet (including its headers).
This hash can return any binary string, which is later compared to
the strings registered with the pcap_register function. The packet
hash callback will normally extract some portion of the packet, such
as its source address.
The pcap reader is instructed to listen for certain packets using the
pcap_register function. The function takes a binary string which is
compared against the hash value of every packet received. Those
packets whose hashes match any registered strings will be returned
by the pcap_receive method. Register the empty string to receive all
packets.
A script receives all packets for which a listener has been registered
by calling the pcap_receive method. The method blocks until a
packet is received or a timeout occurs.
The more general the packet hash computing function is kept, the
more scripts may receive the packet and proceed with their
execution. To handle packet capture inside your script you first have
to create a socket with nmap.new_socket and later close the socket
with socket_object:close—just like with the connection-based
network I/O.
Thread Mutexes
The first step is to create a mutex object using a statement such as:
mutexfn = nmap.mutex(object)
"lock"
"trylock"
"done"
Releases the mutex and allows another thread to lock it. If the
thread does not have a lock on the mutex, an error will be
raised.
"running"
Returns the thread locked on the mutex or nil if the mutex is
not locked. This should only be used for debugging as it
interferes with garbage collection of finished threads.
Exception Handling
result = ""
socket = nmap.new_socket()
catch = function()
socket:close()
end
try = nmap.new_try(catch)
try(socket:connect(host.ip, port.number))
result = try(socket:receive_lines(1))
try(socket:send(result))
The Registry
The Head
The head of the script is essentially its meta information. This
includes the fields: description, categories, runlevel, author, and
license as well as initial NSEDoc information such as usage, args,
and output tags (see the section called “Writing Script
Documentation (NSEDoc)”).
description = [[
Attempts to find the owner of an open TCP port by
querying an auth
(identd - port 113) daemon which must also be open on the
target system.
]]
---
--@output
-- 21/tcp open ftp ProFTPD 1.3.1
-- |_ auth-owners: nobody
-- 22/tcp open ssh OpenSSH 4.3p2 Debian
9etch2 (protocol 2.0)
-- |_ auth-owners: root
-- 25/tcp open smtp Postfix smtpd
-- |_ auth-owners: postfix
-- 80/tcp open http Apache httpd 2.0.61
((Unix) PHP/4.4.7 ...)
-- |_ auth-owners: dhapache
-- 113/tcp open auth?
-- |_ auth-owners: nobody
-- 587/tcp open submission Postfix smtpd
-- |_ auth-owners: postfix
-- 5666/tcp open unknown
-- |_ auth-owners: root
Next come the author, license, and categories tags. This script
belongs to the safe because we are not using the service for
anything it was not intended for. Because this script is one that
should run by default it is also in the default category. Here are the
variables in context:
The Rule
if
identd ~= nil
and identd.state == "open"
and port.protocol == "tcp"
and port.state == "open"
then
return true
else
return false
end
end
The Mechanism
try(client_ident:connect(host.ip, 113))
try(client_service:connect(host.ip, port.number))
try(client_ident:send(request))
owner = try(client_ident:receive_lines(1))
try(client_ident:close())
try(client_service:close())
return owner
end
description = [[
Maps IP addresses to autonomous system (AS) numbers.
---
-- @usage
-- nmap --script asn-query.nse [--script-args dns=<DNS
server>] <target>
-- @args dns The address of a recursive nameserver to use
(optional).
-- @output
-- Host script results:
-- | AS Numbers:
-- | BGP: 64.13.128.0/21 | Country: US
-- | Origin AS: 10565 SVCOLO-AS - Silicon Valley
Colocation, Inc.
-- | Peer AS: 3561 6461
-- | BGP: 64.13.128.0/18 | Country: US
-- | Origin AS: 10565 SVCOLO-AS - Silicon Valley
Colocation, Inc.
-- |_ Peer AS: 174 2914 6461
@param
@see
@return
@usage
@name
@class
@args
@output
@author
This tag, which may be given multiple times, lists the authors
of an NSE module. For scripts, use the author variable instead.
@copyright
description = [[
Detects the Skype version 2 service.
]]
author = "Brandon Enright <[email protected]>"
license = "Same as Nmap--See http://nmap.org/book/man-
legal.html"
categories = {"version"}
require "comm"
If the script detects Skype, it augments its port table with now-
known name and product fields. It then sends this new information
to Nmap by calling nmap.set_port_version. Several other version
fields are available to be set if they are known, but in this case we
only have the name and product. For the full list of version fields,
refer to the nmap.set_port_version documentation.
Notice that this script does nothing unless it detects the protocol. A
script shouldn't produce output (other than debug output) just to
say it didn't learn anything.
description = [[
Attempts to get a list of usernames via the finger
service.
]]
author = "Eddie Bell <[email protected]>"
license = "Same as Nmap--See http://nmap.org/book/man-
legal.html"
The categories field is a table containing all the categories the script
belongs to—These are used for script selection with the --script
option:
You can use the facilities provided by the nselib (the section called
“NSE Libraries”) with require. Here we want to use common
communication functions and shorter port rules:
require "comm"
require "shortport"
Implementation Details
Now it is time to explore the NSE implementation details in depth.
Understanding how NSE works is useful for designing efficient
scripts and libraries. The canonical reference to the NSE
implementation is the source code, but this section provides an
overview of key details. It should be valuable to folks trying to
understand and extend the NSE source code, as well as to script
authors who want to better-understand how their scripts are
executed.
Initialization Phase
During its initialization stage, Nmap loads the Lua interpreter and its
provided libraries. These libraries are fully documented in the Lua
Reference Manual. Here is a summary of the libraries, listed
alphabetically by their namespace name:
debug
io
math
os
The Operating System library provides system facilities such
as filesystem operations (including file renaming or removal
and temporary file creation) and system environment access.
package
string
table
Script Execution
DNS proxying
rules
OS Spoofing
Introduction
The Purpose of a Graphical Frontend for Nmap
Scanning
Profiles
Scan Aggregation
Interpreting Scan Results
Scan Results Tabs
The Nmap Output tab
The Ports / Hosts tab
The Topology tab
The Host Details tab
The Scans tab
Sorting by Host
Sorting by Service
Saving and Loading Scan Results
The Recent Scans Database
Surfing the Network Topology
An Overview of the Topology Tab
Legend
Controls
Action controls
Interpolation controls
Layout controls
View controls
Fisheye controls
Keyboard Shortcuts
The Hosts Viewer
The Profile Editor
Editing a Command
Creating a New Profile
Editing or Deleting a Profile
Searching Saved Results
Comparing Results
Zenmap in Your Language
Creating a new translation
Files Used by Zenmap
The nmap Executable
System Configuration Files
Per-user Configuration Files
Output Files
Description of zenmap.conf
Sections of zenmap.conf
Command-line Options
Synopsis
Options Summary
Error Output
History
Introduction
Zenmap is the official graphical user interface (GUI) for the Nmap
Security Scanner. It is a multi-platform, free and open-source
application designed to make Nmap easy for beginners to use while
providing advanced features for experienced Nmap users.
Frequently used scans can be saved as profiles to make them easy
to run repeatedly. A command creator allows interactive creation of
Nmap command lines. Scan results can be saved and viewed later.
Saved scans can be compared with one another to see how they
differ. The results of recent scans are stored in a searchable
database. A typical Zenmap screen shot is shown in Figure 12.1. See
the official Zenmap web page for more screen shots.
Comparison
Convenience
Repeatability
Zenmap's command profiles make it easy to run the exact
same scan more than once. There's no need to set up a shell
script to do a common scan.
Discoverability
Scanning
Begin Zenmap by typing zenmap in a terminal or by clicking the
Zenmap icon in the desktop environment. The main window, as
shown in Figure 12.2, is displayed.
Profiles
The “Intense scan” is just one of several scan profiles that come
with Zenmap. Choose a profile by selecting it from the “Profile”
combo box. Profiles exist for several common scans. After selecting
a profile the Nmap command line associated with it is displayed on
the screen. Of course, it is possible to edit these profiles or create
new ones. This is covered in the section called “The Profile Editor”.
Scan Aggregation
Zenmap has the ability to combine the results of many Nmap scans
into one view, a feature known as scan aggregation. When one scan
is finished, you may start another in the same window. When the
second scan is finished, its results are merged with those from the
first. The collection of scans that make up an aggregated view is
called a network inventory.
Now results for both scanme and localhost are shown. This is
something you could have done with one Nmap scan, giving both
targets, although it's convenient not to have to think of all the
targets in advance. Now suppose we want some more information
about scanme, so we launch an intense scan on it.
Now scanme has a little penguin icon showing that its operating
system has been detected as Linux. Additionally some of its services
have been identified. Now we're doing something you can't do with
a single Nmap scan, because you can't single out a host for more
intense scanning like we did. The results for localhost are still
present, though we won't know more about it than we did before
unless we decide to do a more in-depth scan.
Each scan window contains five tabs which each display different
aspects of the scan results. They are: “Nmap Output”,
“Ports / Hosts”, “Topology”, “Host Details”, and “Scans”. Each of
these are discussed in this section.
Recall that the results of more than one scan may be shown in a
window (see the section called “Scan Aggregation”). The drop-down
combo box at the top of the tab allows you to select the scan to
display. The “Details” button brings up a window showing
miscellaneous information about the scan, such as timestamps,
command-line options, and the Nmap version number used.
When a service is selected, the “Ports / Hosts” tab shows all the
hosts which have that port open or filtered. This is a good way to
quickly answer the question “What computers are running HTTP?”
Service selection is further described in the section called “Sorting
by Service”.
9 or more open
ports.
The “Scans” tab shows all the scans that are aggregated to make up
the network inventory. From this tab you can add scans (from a file
or directory) and remove scans.
Sorting by Host
Each host is labeled with its host name or IP address and has an
icon indicating the operating system that was detected for that host.
The icon is meaningful only if OS detection (-O) was performed.
Otherwise, the icon will be a default one indicating that the OS is
unknown. Figure 12.5 shows all possible icons. Note that Nmap's OS
detection cannot always provide the level of specificity implied by
the icons; for example a Red Hat Linux host will often be displayed
with the generic Linux icon.
Above the same list that contains all the scanned hosts is a button
labeled “Services”. Clicking that will change the list into a list of all
ports that are open, filtered, or open|filtered on any of the targets,
as shown in Figure 12.6. (Ports that were not listed explicitly in
Nmap output are not included.) The ports are identified by service
name (http, ftp, etc.). The list can be sorted by clicking the header
of the list.
Selecting a host will cause the “Ports / Hosts” tab to display all the
hosts that have that service open or filtered.
You can save every scan in an inventory with “Save All Scans to
Directory” under the “Scan” menu (ctrl+alt+S). When saving an
inventory for the first time, you will commonly create a new
directory using the “Create Folder” button in the save dialog. In
subsequent saves you can continue saving to the same directory. To
reduce the chance of overwriting unrelated scan files, the save-to-
directory function will refuse to continue if the chosen directory
contains a file that doesn't belong to the inventory. If you are sure
you want to save to that directory, delete any offending files and
then save again.
Saved results are loaded by choosing “Open Scan” from the “Scan”
menu, or by typing the ctrl+O keyboard shortcut. In the file
selector, the “Open” button opens a single scan, while the “Open
Directory” button opens every file in the chosen directory (perhaps
created using “Save All Scans to Directory”).
Scan results that are not saved to a file are automatically stored in a
database. Scan results that are loaded from a file, and are then
modified (such as by the addition of a host comment) but not re-
saved, are also stored in the database. The database is stored in a
file called zenmap.db and its location is platform-dependent (see the
section called “Files Used by Zenmap”). By default, scans are kept in
the database for 60 days and then removed. This time interval can
be changed by modifying the value of the save_time variable in the
[search] section of zenmap.conf (see the section called “Description
of zenmap.conf”).
Legend
The topology view uses many symbols and color conventions. This
section explains what they mean.
Each regular host in the network is represented by a little
circle. The color and size of the circle is determined by the
number of open ports on the host. The more open ports, the
larger the circle. A white circle represents an intermediate host
in a network path that was not port scanned. If a host has
fewer than three open ports, it will be green; between three
and six open ports, yellow; more than six open ports, red.
If a host is a router, switch, or wireless access point, it is drawn
with a square rather than a circle.
Controls
Action controls
The controls in the “Action” section control what happens when you
click on a host. The buttons in this section are, from left to right,
“Change focus”, “Show information”, “Group children”, and “Fill
region”. When the mode is “Change focus”, clicking on a host
rearranges the display to put the selected host at the center. When
the mode is “Show information”, clicking on a host brings up a
window with information about it.
Interpolation controls
Layout controls
There are two options for the automatic layout of nodes. Symmetric
mode gives each subtree of a host an equal-sized slice of the graph.
It shows the network hierarchy well but hosts far from the center
can be squeezed close together. Weighted mode gives hosts with
more children a larger piece of the graph.
View controls
Fisheye controls
Keyboard Shortcuts
Key Function
c Return the display to the center host.
a Show or hide host addresses.
h Show or hide hostnames.
i Show or hide host icons.
l Show or hide latency.
r Show or hide the rings.
Editing a Command
To run the new command line, click the “Scan” button. This will copy
the command to the main window, dismiss the profile editor, and
start running the scan. To make further changes to the command,
just select “New Profile or Command” again, remembering that it
will use whatever command is shown on the screen.
The procedure for creating a new profile is almost the same as for
editing a command. Select “New Profile or Command” from the
“Profile” menu and edit the command as you wish. Then, instead of
clicking “Scan”, go to the “Profile” tab and give a name to the
profile. Then click “Save Changes” to save the new profile.
A profile may or may not include scan targets. If you often run the
same scan against the same set of targets, you will find it
convenient to list the targets within the profile. If you plan to run the
same scan against different targets, leave the “Targets” field blank,
and fill in the targets later, when you run the scan.
To edit a profile, select the profile you want to edit, then choose
“Edit Selected Profile” from the “Profile” menu or use the ctrl+E
keyboard shortcut. The profile editor will open, this time with the
name and description filled from the profile selected. Click “Save
Changes” to save any changes or “Cancel” to leave without saving.
When you open the profile editor using “Edit Selected Profile”, an
additional “Delete” button will be present at the bottom. Zenmap
will present a warning before deleting the profile.
Searching Saved Results
Zenmap allows you to search saved scan results files and the
database of recent scans. To begin searching, select “Search Scan
Results” from the “Tools” menu or use the ctrl+F keyboard shortcut.
The search dialog appears as shown in Figure 12.11.
The search interface initially shows all the scans in the recent scans
database (for which see the section called “The Recent Scans
Database”). The reason all the scans are shown is simple—no
restrictions have yet been placed on the search, so every possible
result is returned.
You will have noticed that whenever you choose a search expression
a text representation of it appears in the search entry. The string in
the “Search” field is what really controls the search; the
“Expressions” interface is just a convenient way to set it. When you
have learned what search strings correspond to what expressions,
you may skip the expressions interface and just type in a search
string directly.
<keyword>
Port states
Matches scans of any hosts with the given name. The name
may be either the name specified in the scan or the reverse-
DNS name of any host.
os:<string>
Matches scans of hosts with the given string in any part of the
service description of any of their ports. service:ssh will return
scans of hosts running any type of SSH.
Comparing Results
It is a common desire to run the same scan twice at different times,
or run two slightly different scans at the same time, and see how
they differ. Zenmap provides an interface for comparing scan
results, shown in Figure 12.14. Open the comparison tool by
selecting “Compare Results” from the “Tools” menu or by using the
ctrl+D (think “diff”) keyboard shortcut. Zenmap supports
comparing two scan results at a time.
export LANG=de
{ LANG=de; }
Then from the “Format” menu choose “Make Plain Text”. Open the
“Save” dialog, select your home directory and click “New Folder”.
Create a folder called .MacOSX and click past the warning that
appears. Save the file with the name environment.plist, and insist
on the extension .plist in the next warning that appears. Finally, log
out and back in to make the change take effect. A portion of this
process is shown in Figure 12.18.
Let's say you are going to make a translation into Spanish, which
has the language code “es”. Within the Zenmap source tree there is
a plain-text file share/zenmap/locale/zenmap.pot containing all the
translatable strings in the application. You create a new portable
object (.po) file by running msginit -l es.po -i zenmap.pot. The
new es.po file contains all the application's English strings followed
by blank strings where you fill in the appropriate translations.
To test the portable object file you must turn it into a machine
object (.mo) file. Create the directory es/LC_MESSAGES and then run
msgfmt es.po -o es/LC_MESSAGES/zenmap.mo. With this file in
place Zenmap will use your translation when LANG is set properly. To
update the portable object file when zenmap.pot changes, run
msgmerge -U es.po zenmap.pot. This will add new strings and
mark any obsolete strings so they can be removed.
[paths]
nmap_command_path = /opt/bin/nmap
[paths]
nmap_command_path = nmap-custom
config/
docs/
locale/
misc/profile_editor.xml
These files affect only one user of Zenmap. Some of them are
copied from the config subdirectory of the system files when
Zenmap is run for the first time. Per-user files are in
<HOME>/.zenmap on Unix and Mac OS X, where <HOME> is the
current user's home directory. They are in
C:\Users\<USER>\.zenmap on Windows Vista and
C:\Documents and Settings\<USER>\.zenmap on previous versions
of Windows, where <USER> is the name of the current user.
recent_scans.txt
scan_profile.usp
target_list.txt
zenmap.conf
zenmap.db
zenmap_version
Output Files
Description of zenmap.conf
[output_highlight]
enable_highlight = True
[paths]
nmap_command_path = nmap
ndiff_command_path = ndiff
[search]
search_db = 1
file_extension = xml
store_results = 1
directory =
save_time = 60;days
Sections of zenmap.conf
Boolean values are normalized from True, true, or 1 to true or
anything else to false.
[paths]
nmap_command_path
ndiff_command_path
[search]
The [search] section defines how the search tool (see the
section called “Searching Saved Results”) behaves. The
names in this section correspond to the options in the “Search
options” tab of the search dialog. It has the following names
defined.
directory
file_extension
search_db
store_results
A Boolean controlling whether to store scan results in the
recent scans database. See the section called “The Recent
Scans Database”.
save_time
[diff]
The [diff] section defines how the comparison tool (see the
section called “Comparing Results”) behaves. It has the
following names defined.
diff_mode
colored_diff
[diff_colors]
[output_highlight]
regex
bold
italic
underline
text
highlight
Command-line Options
Being a graphical application, most of Zenmap's functionality is
exposed through its graphical interface. Zenmap's command-line
options are given here for completeness and because they are
sometimes useful. In particular, it's good to know that the command
zenmap <results file> starts Zenmap with the results in <results
file> already open.
Synopsis
Options Summary
Open the given results file for viewing. The results file may be
an Nmap XML output file (.xml, as produced by nmap -oX), or
a file previously saved by Zenmap.
-h, --help
Start with the given profile selected. The profile name is just a
string: "Regular scan". If combined with -t, begin a scan with
the given profile against the specified target.
Start with the given target. If combined with -p, begin a scan
with the given profile against the specified target.
-v, --verbose
Increase verbosity (of Zenmap, not Nmap). This option may be
given multiple times for even more verbosity printed to the
console window used to start Zenmap.
Error Output
History
Zenmap was originally derived from Umit, an Nmap GUI created
during the Google-sponsored Nmap Summer of Code in 2005 and
2006. The primary author of Umit was Adriano Monteiro Marques.
When Umit was modified and integrated into Nmap in 2007, it was
renamed Zenmap.
Introduction
Command-line Flags
Controlling Output Type
Controlling Verbosity of Output
Enabling Debugging Output
Handling Error and Warning Messages
Enabling Packet Tracing
Resuming Aborted Scans
Interactive Output
Normal Output (-oN)
$crIpT kIddI3 0uTPut (-oS)
XML Output (-oX)
Using XML Output
Manipulating XML Output with Perl
Output to a Database
Creating HTML Reports
Saving a Permanent HTML Report
Grepable Output (-oG)
Grepable Output Fields
Host field
Ports field
Protocols field
Ignored State field
OS field
Seq Index field
IP ID Seq field
Status field
Parsing Grepable Output on the Command Line
Introduction
A common problem with open-source security tools is confusing and
disorganized output. They often spew out many lines of irrelevant
debugging information, forcing users to dig through pages of output
trying to discern important results from the noise. Program authors
often devote little effort to organizing and presenting results
effectively. The output messages can be difficult to understand and
poorly documented. This shouldn't be too surprising—writing clever
code to exploit some TCP/IP weakness is usually more gratifying
than documentation or UI work. Since open source authors are
rarely paid, they do what they enjoy.
While this does get the job done, it is difficult to interpret. Output is
printed based on when the response was received, without any
option for sorting the port numbers or even grouping all open ports
on a target host together. A bunch of space is wasted near the
beginning of each line and no summary of results is provided.
Nmap's output is also far from perfect, though I do try pretty hard to
make it readable, well-organized, and flexible. Given the number of
ways Nmap is used by people and other software, no single format
can please everyone. So Nmap offers several formats, including the
interactive mode for humans to read directly and XML for easy
parsing by software.
Command-line Flags
As with almost all other Nmap capabilities, output behavior is
controlled by command-line flags. These flags are grouped by
category and described in the following sections.
Interactive output
While these options save results to files, Nmap still prints interactive
output to stdout as usual. For example, the command nmap -oX
myscan.xml target prints XML to myscan.xml and fills standard
output with the same interactive results it would have printed if -oX
wasn't specified at all. You can change this by passing a hyphen
character as the argument to one of the format types. This causes
Nmap to deactivate interactive output, and instead print results in
the format you specified to the standard output stream. So the
command nmap -oX - target will send only XML output to stdout.
Serious errors may still be printed to the normal error stream, stderr.
Unlike some Nmap arguments, the space between the logfile option
flag (such as -oX) and the filename or hyphen is mandatory. If you
omit the flags and give arguments such as -oG- or -oXscan.xml, a
backwards compatibility feature of Nmap will cause the creation of
normal format output files named G- and Xscan.xml respectively.
After deciding which format(s) you wish results to be saved in, you
can decide how detailed those results should be. The first -v option
enables verbosity with a level of one. Specify -v twice for a slightly
greater effect. Verbosity levels greater than two aren't useful. Most
changes only effect interactive output, and some also affect normal
and script kiddie output. The other output types are meant to be
processed by machines, so Nmap can give substantial detail by
default in those formats without fatiguing a human user. However,
there are a few changes in other modes where output size can be
reduced substantially by omitting some detail. For example, a
comment line in the grepable output that provides a list of all ports
scanned is only printed in verbose mode because it can be quite
long. The following list describes the major changes you get with at
least one -v option.
Scan completion time estimates
On scans that take more than a minute or two, you will see
occasional updates like this in interactive output mode:
Additional warnings
Additional notes
Birthday wishes
The changes that are usually only useful until Nmap finishes and
prints its report are only sent to interactive output mode. If you send
normal output to a file with -oN, that file won't contain open port
alerts or completion time estimates, though they are still printed to
stdout. The assumption is that you will review the file when Nmap is
done and don't want a lot of extra cruft, while you might watch
Nmap's execution progress on standard output and care about
runtime progress. If you really want everything printed to stdout
sent to a file, use the output stream redirection provided by your
shell (e.g. nmap -v scanme.nmap.org > scanoutput.nmap).
The following two examples put all of this together. Example 13.3
shows the output of a normal scan without the -v option.
Example 13.4 is the output of the same scan with verbosity enabled.
Features such as the extra OS identification data, completion time
estimates, open port alerts, and extra informational messages are
easily identified in the latter output. This extra info is often helpful
during interactive scanning, so I always specify -v when scanning a
single machine unless I have a good reason not to.
When even verbose mode doesn't provide sufficient data for you,
debugging is available to flood you with much more! As with the
verbosity option (-v), debugging is enabled with a command-line
flag (-d) and the debug level can be increased by specifying it
multiple times. Alternatively, you can set a debug level by giving an
argument to -d. For example, -d9 sets level nine. That is the highest
effective level and will produce thousands of lines unless you run a
very simple scan with very few ports and targets.
The remainder of each line is protocol specific. As you can see, ICMP
provides a human-readable type if available (echo request in this
case) followed by the ICMP type and code values. The ICMP packet
logs end with the IP TTL, ID, and packet length field. TCP packets use
a slightly different format after the destination IP and port number.
First comes a list of characters representing the set TCP flags. The
flag characters are SAFRPUEC, which stand for SYN, ACK, FIN, RST,
PSH, URG, ECE, and CWR, respectively. The latter two flags are part
of TCP explicit congestion notification, described in RFC 3168.
Some extensive Nmap runs take a very long time—on the order of
days. Such scans don't always run to completion. Restrictions may
prevent Nmap from being run during working hours, the network
could go down, the machine Nmap is running on might suffer a
planned or unplanned reboot, or Nmap itself could crash. The
administrator running Nmap could cancel it for any other reason as
well, by pressing ctrl-C. Restarting the whole scan from the
beginning may be undesirable. Fortunately, if normal (-oN) or
grepable (-oG) logs were kept, the user can ask Nmap to resume
scanning with the target it was working on when execution ceased.
Specify the --resume option and pass the normal/grepable output
file as its argument. No other arguments are permitted, as Nmap
parses the output file to use the same ones specified previously.
Simply call Nmap as nmap --resume <logfilename>. Nmap will
append new results to the data files specified in the previous
execution.
This feature does have some limitations. Resumption does not
support the XML output format because combining the two runs into
one valid XML file would be difficult. This feature only skips hosts for
which all scanning was completed. If a scan was in progress against
a certain target when Nmap was stopped, the --resume will restart
scanning of that host from the beginning.
Interactive Output
Interactive output is what Nmap prints to the stdout stream, which
usually appears on the terminal window you executed Nmap from.
In other circumstances, you might have redirected stdout to a file or
another application such as Nessus or an Nmap GUI may be reading
the results. If a larger application is interpreting the results rather
than printing Nmap output directly to the user, then using the XML
output discussed in the section called “XML Output (-oX)” would be
more appropriate.
This format has but one goal: to present results that will be valuable
to a human reading over them. No effort is made to make these
easily machine parsable or to maintain a stable format between
Nmap versions. Better formats exist for these things. The toughest
challenge is deciding which information is valuable enough to print.
Omitting data that a user wants is a shame, though flooding the
user with pages of mostly irrelevant output can be even worse. The
verbosity, debugging, and packet tracing flags are available to shift
this balance based on individual users' preferences.
Some humor-impaired people take this option far too seriously, and
scold me for catering to script kiddies. It is simply a joke making fun
of the script kiddies—they don't actually use this mode (I hope).
There are a few aspects of the example XML output which may not
be self-explanatory. For example, look at the two port elements in
Example 13.10
The port protocol, ID (port number), state, and service name are the
same as would be shown in the interactive output port table. The
service product, version, and extrainfo attributes come from version
detection and are combined together into one field of the interactive
output port table. The method and conf attributes aren't present in
any other output types. The method can be table, meaning the
service name was simply looked up in nmap-services based on the
port number and protocol, or it can be probed, meaning that it was
determined through the version detection system. The conf attribute
measures the confidence Nmap has that the service name is
correct. The values range from one (least confident) to ten. Nmap
only has a confidence level of three for ports determined by table
lookup, while it is highly confident (level 10) that port 80 of
Example 13.10, “Nmap XML port elements” is Apache httpd,
because Nmap connected to the port and found a server exhibiting
the HTTP protocol with Apache banners.
One other aspect that some users find confusing is that the
attributes /nmaprun/@start and /nmaprun/runstats/finished/@time
hold timestamps given in Unix time, the number of seconds since
January 1, 1970. This is often easier for programs to handle. For the
convenience of human readers, versions 3.78 and newer include the
equivalent calendar time written out in the attributes
/nmaprun/@startstr and /nmaprun/runstats/finished/@endstr.
A key advantage of XML is that you do not need to write your own
parser as you do for specialized Nmap output types such as
grepable and interactive output. Any general XML parser should do.
The XML parser that people are most familiar with is the one in your
web browser. Both IE and Mozilla/Firefox include capable parsers
that can be used to view Nmap XML data. Using them is as simple
as typing the XML filename or URL into the address bar. Figure 13.1
shows an example of XML output rendered by a web browser. How
this automatic rendering works and how to save a permanent copy
of an HTML report is covered in the section called “Creating HTML
Reports”.
The language with the best custom Nmap XML support is Perl. Max
Schubert (affectionately known as Perldork) has created a module
named Nmap::Scanner while Anthony Persaud created
Nmap::Parser. These two modules have many similarities: they can
execute Nmap themselves or read from an output file, are well
documented, come with numerous example scripts, are part of the
Comprehensive Perl Archive Network (CPAN), and are popular with
users. They each offer both a callback based parser for interpreting
data as Nmap runs as well as an all-at-once parser for obtaining a
fully parsed document once Nmap finishes executing. Their APIs are
a bit different—Nmap::Scanner relies on type-safe classes while
Nmap::Parser relies on lighter-weight native Perl arrays. I
recommend looking at each to decide which best meets your needs
and preferences.
use Nmap::Parser;
#PARSING
my $np = new Nmap::Parser;
$nmap_exe = '/usr/bin/nmap';
$np->parsescan($nmap_exe,'-sT -p1-1023', @ips);
#or
$np->parsefile('nmap_output.xml'); #using filenames
sub scan_started {
my $self = shift;
my $host = shift;
my $hostname = $host->name();
my $addresses = join(', ', map {$_->address()} $host-
>addresses());
my $status = $host->status();
sub port_found {
my $self = shift;
my $host = shift;
my $port = shift;
my $name = $host->name();
my $addresses = join(', ', map {$_->addr()} $host-
>addresses());
Output to a Database
A common desire is to output Nmap results to a database for easier
queries and tracking. This allows users from an individual
penetration tester to an international enterprise to store all of their
scan results and easily compare them. The enterprise might run
large scans daily and schedule queries to mail administrators of
newly open ports or available machines. The penetration tester
might learn of a new vulnerability and search all of his old scan
results for the affected application so that he can warn the relevant
clients. Researchers may scan millions of IP addresses and keep the
results in a database for easy real-time queries.
While these goals are laudable, Nmap offers no direct database
output functionality. Not only are there too many different database
types for me to support them all, but users' needs vary so
dramatically that no single database schema is suitable. The needs
of the enterprise, pen-tester, and researcher all call for different
table structures.
How does the web browser know how to convert XML to HTML? An
Nmap XML output file usually contains a reference to an XSL
stylesheet called nmap.xsl that describes how the transformation
takes place.
The XML processing instruction that says where the stylesheet can
be found will look something like
<?xml-stylesheet href="/usr/share/nmap/nmap.xsl"
type="text/xsl"?>
Such a stylesheet reference will work fine when viewing scan results
on the same machine that initiated the scan, but it will not work if
the XML file is transferred to another machine where the nmap.xsl
file is in a different place or absent entirely. To make the XML styling
portable, give the --webxml option to Nmap. This will change the
processing instruction to read
<?xml-stylesheet href="http://nmap.org/data/nmap.xsl"
type="text/xsl"?>
The resultant XML output file will render as HTML on any web-
connected machine. Using the network location in this fashion is
often more useful, but the local copy of nmap.xsl is used by default
for privacy reasons.
While web browsers can display an HTML view of Nmap XML, they
don't usually make it easy to save the generated HTML to a file. For
that a standalone XSLT processor is required. Here are commands
that turn an Nmap XML output file into an HTML file using common
XSLT processors.
xsltproc
Xalan
The host line is split into fields, each of which consist of a field name
followed by a colon and space, then the field content. The fields are
separated by tab characters (ASCII number nine, '\t').
Example 13.13, “A typical example of grepable output” shows six
fields: Host, Ports, Ignored State, OS, Seq Index, and IP ID. A Status
section is included in list (-sL) and ping (-sP) scans, and a Protocols
section is included in IP protocol (-sO) scans. The exact fields given
depend on Nmap options used. For example, OS detection triggers
the OS, Seq Index, and IP ID fields. Because they are tab delimited,
you might split up the fields with a Perl line such as:
Host field
The Host field always comes first and is included no matter what
Nmap options are chosen. The contents are the IP address (an IPv6
address if -6 was specified), a space, and then the reverse DNS
name in parentheses. If no reverse name is available, the
parentheses will be empty.
Ports field
Port number
State
The same port state which would appear in the normal output
port table is shown here.
Protocol
Owner
Service
SunRPC info
Version info
Protocols field
The IP protocol scan (-sO) has a Protocols field rather than Ports. Its
contents are quite similar to the Ports field, but it has only three
subfields rather than seven. They are delimited with slashes, just as
with the Ports field. Any slashes that would appear in a subfield are
changed into pipes (|), also as done in the Ports field. The subfields
are protocol number, state, and protocol name. These correspond to
the three fields shown in interactive output for a protocol scan. An
example of IP protocol scan grepable output is shown in
Example 13.14. The Host line, which would normally be all one line,
is here wrapped for readability.
Example 13.14. Grepable output for IP protocol scan
To save space, Nmap may omit ports in one non-open state from the
list in the Ports field. Nmap does this in interactive output too.
Regular Nmap users are familiar with the lines such as “The 1658
ports scanned but not shown below are in state: filtered”. For
grepable mode, that state is given in the Ignored State field.
Following the state name is a space, then in parentheses is the
number of ports found in that state.
OS field
IP ID Seq field
Status field
Example: Status: Up
Ping and list scans contain only two fields in grepable mode: Host
and Status. Status describes the target host as either Up, Down, or
Unknown. List scan always categorizes targets as Unknown because
it does not perform any tests. Ping scan lists a host as up if it
responds to at least one ping probe, and down if no responses are
received. It used to also report Smurf if ping probes sent to the
target resulted in one or more responses from other hosts, but that
is no longer done. Down hosts are only shown when verbosity is
enabled with -v. Example 13.15 demonstrates a ping scan of 100
random hosts, while Example 13.16 demonstrates a list scan of five
hosts.