Penetration testing

Nmap Cheat Sheet 5: The Final View of a Ninja Pentester

May 6, 2015 by

As we discussed in the last topic of our Nmap Series, this will be our final touch for the cheat sheet. Here we will try to cover most of the topic as required for Vulnerability Assessment and Penetration Testing.

As a Ninja Pentester, we will start with following:

What should you learn next?

What should you learn next?

From SOC Analyst to Secure Coder to Security Manager — our team of experts has 12 free training plans to help you hit your goals. Get your free copy now.

Database auditing

In cases of web applications where storing, editing, updating, and deleting in an information database is used. During pentesting for database we can use Nmap NSE for exploiting and securing the database in a real time scenario. After getting root access, what can we do, or is it possible to attack the database from outside? These questions can be easily answered by the following way.

List of database names:

nmap -sV --script=mysql-databases

The above lists the database name in MySQL setup and only works if username and password are null.

Arguments like username and password can be set to find databases for further post exploitation.

nmap -sV --script=mysql-databases --script-args mysqluser=root,mysqlpass=toor

User Auditing:

The password to use for authentication. If unset it attempts to use credentials found by mysql-brute or mysql-empty-password.

nmap -sV --script=mysql-users

Arguments like username and password can be set to find databases for further post exploitation.

MySQL empty password for root access:

It checks for MySQL servers with an empty password for root or anonymous.

sudo nmap --script mysql-empty-password

See how beautifully we got the username and password. Here an attacker can do further exploitation.

Like above we can do a database audit or pentesting for different database like mysql, sql server, oracle etc. A list of scripts is available on NSE documentation on the Nmap site.

Listing mysql server variables:

The developer or DBA people by default forgot to set the correct environment setting for the database. The following can be used to retrieve the environment setting.

nmap -p3306 --script mysql-variables localhost

Brute forcing:

We can also use the Nmap script for bruteforcing mysql user and password in case of default credentials.

nmap --script=mysql-brute localhost.

Basically it checks the root and toor credentials as described by image.

Dump Hashes:

Dumps the password hashes from an MySQL server in a format suitable for cracking by tools such as John the Ripper. Appropriate DB privileges (root) are required. The username and password arguments take precedence over credentials discovered by the mysql-brute and mysql-empty-password scripts.

nmap --script=mysql-dump-hashes localhost

Mysql info:

As a pentester we can get mysql info for further exploitation.

nmap --script=mysql-info localhost

Mysql Enumeration:

After we get root on a remote computer, we can gather valid username and additional information.

nmap --script=mysql-enum localhost

It is going and going for enumeration. See the next picture:

Voila. We got some info right……..

Exploiting CVE-2012-2122

Remember the most serious vulnerability in mysql is CVE-2012-2122, where an attacker can get root access only by knowing username, and after 300 attempt of password an attacker can login to the database. For more information click below.

So we have a module in NSE for exploiting this vulnerability.

nmap --script=mysql-vuln-cve2012-2122 localhost

Our bad luck. Port is filtered. So let's trace the program. I am thinking as a reverse engineer, so I put a debug (-d) option to see more (see the above picture). It seems that there is no response from victim though the port is filtered. So use ninja skills to attack.

One more thing I want to say for vul, you can search shodan.

Pen testing mail servers

Mail servers are often used by organisations and by default they have known and unknown vulnerabilities. So an attacker can do a mail server exploitation by using an Nmap scipt engine. Moreover these organizations have default configuration like credentials, services, weak string in nmp etc., so let's do our work.

We can do the below things:

  • Discovering valid e-mail accounts using Google Search
  • Detecting open relays
  • Brute forcing SMTP passwords
  • Enumerating users in an SMTP server
  • Detecting backdoor SMTP servers
  • Brute forcing IMAP passwords
  • Retrieving the capabilities of an IMAP mail server
  • Brute forcing POP3 passwords
  • Retrieving the capabilities of a POP3 mail server
  • Detecting vulnerable Exim SMTP servers version 4.70 through 4.75

Discovering valid e-mail accounts using Google Search

To find valid e-mail accounts using Google Search and Google Groups by using Nmap, enter the following command:

nmap -p80 --script=http-email-harvest target

Detecting open relays

What is Open Relay?

An open relay in the SMTP is a type of configuration where anyone on the Internet can send email through it. This used to be the default configuration in many mail servers. These are very popular among hackers and spammers to do spamming. And these lead to attacks like MITM, or classic relay attack, wherein communication with both parties is initiated by the attacker who then merely relays messages between the two parties without manipulating them or even necessarily reading them.

Now it is clearly mentioned in the figure that a spammer can use SMTP services for Open Relay attack for spamming. Nmap introduced a technique for detecting by the following command:

nmap -sV --script smtp-open-relay -v localhost

Brute forcing SMTP passwords:

Mail servers often store very sensitive information, and penetration testers need to perform brute force password auditing against them to check for weak passwords.

nmap -p25 -Pn --script smtp-brute target

Enumerating users in an SMTP server

E-mail accounts used as usernames are very common in web applications, and finding them is a necessary task when auditing mail servers. Enumerating users via SMTP commands can obtain excellent results, and thanks to the Nmap Scripting Engine we can automate this task.

nmap -p25 –script smtp-enum-users target

Detecting backdoor SMTP servers

Compromised servers might have rogue SMTP servers installed and abused by spammers. System administrators can use Nmap to help them monitor mail servers in their network.

nmap -sV --script smtp-strangeport target

The above results are the answer for one of the biggest companies on the Internet. See how they are vulnerable.

Brute forcing IMAP passwords:

E-mail accounts store very sensitive information and penetration testers auditing a mail server must detect weak passwords that could compromise e-mail accounts and the information accessible through them.

nmap -p143 --script imap-brute target

Retrieving the capabilities of an IMAP mail server:

IMAP servers may support different capabilities. There is a command named CAPABILITY that allows clients to list these supported mail server capabilities, and we can use Nmap to automate this task.

nmap -p143,993 -Pn --script imap-capabilities target

Brute forcing POP3 passwords

E-mail accounts store sensitive information. Penetration testers auditing mail servers must test for weak passwords that could help attackers compromise important accounts. Here we are auditing a POP3 protocol.

nmap -p110 --script pop3-brute

The above gives different server names that have POP3 implementation, which can help an attacker for further exploitation.

Retrieving the capabilities of a POP3 mail server

POP3 mail servers may support different capabilities defined in RFC 2449. By using a POP3 command we can list them, and thanks to Nmap, we can automate this task and include this service information in our scan results.

nmap -p110 --script pop3-capabilities target

Detecting vulnerable Exim SMTP servers version 4.70 through 4.75

Exim SMTP servers 4.70 through 4.75 with DKIM enabled are vulnerable to a format string bug that allows remote attackers to execute code. Nmap NSE can help penetration testers to detect this vulnerability remotely.

nmap --script smtp-vuln-cve2011-1764 --script-args mailfrom=<Source address>,mailto=<Destination address>,domain=<domain> -p25,465,587 <target>

Nmap Script Engine Development (NSE)

So far we have learned the power of NSE and we also knew how powerful this is. Nmap's NSE can be used to develop custom script while doing penetration testing of the network and web applications.

We already discussed different types of inbuilt script for pentesting, so here we will not discuss more about this, instead we can discuss more about developing a custom Nmap Script Engine while attacking the target. Basically NSE is developed by LUA scripting language.

Nmap Script Format:

NSE scripts consist of 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.

description Field:

This field describes what a script is for. Depending upon the author this may be longer or shorter.

categories Field:

This field describes which script belongs to which categories. Please see below demonstration

categories = {"default", "discovery", "safe"}

author Field:

This field describes the owner of script and contact information.

License Field

The license field helps ensure that we have legal permission to distribute all the scripts that come with Nmap. All of those scripts currently use the standard Nmap license and this is optional field. They include the following lines as a standard.

license = "Same as Nmap--See"

dependencies Field

The dependencies field is an array containing the names of scripts that should run before this script if they are also selected. This is used when one script can make use of the results of another. For example, most of the smb-* scripts depend on smb-brute, because the accounts found by smb-brute may allow the other scripts to get more information. Listing a script in dependencies doesn't cause that script to be run; it still has to be selected through the --script option or otherwise. Dependencies merely force an ordering among the scripts that are selected. This is an example of a dependencies table, from smb-os-discovery:

dependencies = {"smb-brute"}


Nmap uses the script rules to determine whether a script should be run against a target. A rule is a Lua function that returns either true or false. The script action function is only performed if the rule evaluates to true.

A script must contain one or more of the following functions that determine when the script will be run:



portrule(host, port)


prerule scripts run once, before any hosts are scanned, during the script pre-scanning phase. hostrule and portrule scripts run after each batch of hosts is scanned. postrule scripts run once after all hosts have been scanned, in the script post-scanning phase. A script may run in more than one phase if it has several rules.


The action is the heart of an NSE script. It contains all of the instructions to be executed when the script's prerule, portrule, hostrule or postrule triggers. It is a Lua function which accepts the same arguments as the rule. The return value of the action value may be a table of name–value pairs, a string, or nil, which covers Nmap API

Environment Variables

Each script has its own set of environment variables:


Describes The script path.


Describes The script name. This variable can be used in debug output.


Since a script can have multiple rule functions, this environment variable will show which rule has activated the script. This would be useful if the script wants to share some code between different Script Scan phases. It will take one of these four string values: "prerule","hostrule", "portrule" or "postrule". This variable is only available during and after the evaluation of the rule functions.

Listing All Libraries:

Lua helps a lot during development. But NSE himself have inbuilt libraries for NSE development. They have their own directory nselib. Some of libraries are listed below. Developers can use these fields/libraries to develop their custom attack scripts. The below are the few libraries.


This library was written by Patrik Karlsson <> to facilitate communication with the Apple AFP Service. It is not feature complete and still missing several functions.


A basic AJP 1.3 implementation based on documentation available from Apache mod_proxy_ajp;


The AMQP library provides some basic functionality for retrieving information about an AMQP server's properties.


ASN.1 functions.


Base32 encoding and decoding. Follows RFC 4648.


Base64 encoding and decoding. Follows RFC 4648.


Pack and unpack binary data.


Bitwise operations on integers.


This library implements a minimal subset of the BitCoin protocol. It currently supports the version handshake and processing Addr responses.


Bittorrent and DHT protocol library which enables users to read information from a torrent file, decode bencoded (bittorrent encoded) buffers, find peers associated with a certain torrent and retrieve nodes discovered during the search for peers.


An implementation of the Canon BJNP protocol used to discover and query Canon network printers and scanner devices.


The brute library is an attempt to create a common framework for performing password guessing against remote services.


Library methods for handling Cassandra Thrift communication as a client.


This module was written by Patrik Karlsson and facilitates communication with the Citrix XML Service. It is not feature complete and is missing several functions and parameters.


Common communication functions for network discovery tasks like banner grabbing and data exchange.


The credential class stores found credentials in the Nmap registry.


A minimal CVS (Concurrent Versions System) pserver protocol implementation which currently only supports authentication.


Read and parse some of Nmap's data files: nmap-protocols, nmap-rpc, nmap-services, and nmap-mac-prefixes.


Implement a Dynamic Host Configuration Protocol (DHCP) client.

For more libraries we can follow the below links:

Nmap API

API for Nmap is a great thing for security researchers and pentesters, where a security developer can define his own custom setting during scan and exploitation. Nmap has learned about the target hosts. This data is passed as arguments to the NSE script's action method. The arguments, host and port are Lua tables, which contain information on the target against which the script is executed. If a script matched a hostrule, it gets only the host table, and if it matches a portrule it gets both host and port.

See the follow rules which should be maintained in the API.


This table is passed as a parameter to the rule and action functions. It contains OS details.


it describes an array of OS match tables, and shows in the follow manner. See below:


host.os = {


name = <string>,----Linux 2.6/3.2

classes = {


vendor = <string>,------Linux

osfamily = <string>,-------Linux

osgen = <string>,------2.6.x

type = <string>,---------general purpose

cpe = {---------------------"cpe:/o:linux:linux_kernel:3"


[More CPE]



[More classes]



[More OS matches]



Similarl to host.os are different sub component available for Nmap API like host.ip,, host.region etc. For full components we can follow the link here:

Network API Connect:

To allow for efficient and parallelizable network I/O, NSE provides an interface to Nsock, the Nmap socket library. The smart callback mechanism Nsock uses is fully transparent to NSE scripts. The main benefit of NSE's sockets is that they never block on I/O operations, allowing many scripts to be run in parallel.

Connect API:

This is a part of network API which is very classical during a TCP/UDP/HTTP/HTTPS connection, which is handled by an irrespective NMAP library. Below is the demonstration of connect API and how it is implemented:


local socket = nmap.new_socket()


try = nmap.new_try(function() socket:close() end)

try(socket:connect(host.ip, port.number))


response = try(socket:receive())


Exception Handling:

Nmap LUA language doesn't have any exception handling mechanism, so API provides great support for exception handling.

local result, socket, try, catch

result = ""

socket = nmap.new_socket()

catch = function()



try = nmap.new_try(catch)

try(socket:connect(host.ip, port.number))

result = try(socket:receive_lines(1))



So like you I am feeling bored with a lot of theory, so let's have some practical sessions. Here I will demonstrate a basic NSE script.

Please read all basic prerequisites for .nse file development (

I will automate all scanning stuff and exploiting through a .nse file, you know the old days of hacking like going through someone's camera that may be private or public. The most popular one is hijacking an AXIS camera. I am demonstrating the technique below.

Use the dork:  inurl:axis-cgi/jpg

Open the URL having axis-cgi/jpg/image.cgi and you can see someone's private or public camera which is unauthorized. See the example below:

So let's exploit in the wild by Nmap NSE development. We know that Axis has vulnerabilities which can be exploitable. So let's start our game:

  1. Create axis.nse file and write the following code which can be used for automation.

    description = [[Attempts to detect webcams AXIS vulnerable to unauthenticated access to the video stream by queryingthe URI " /axis-cgi/jpg/image.cgi ".

  2. We load the library that is needed for our development.

    local http = require "http"

    local shortport = require "shortport"

    local stdnse = require "stdnse"

  3. We define our execution rule as below, which is for our webserver that is needed by Nmap.

    portrule = shortport.http

  4. We determine the status whether the server is vulnerable or not by sending status code 200 or 404.

    action = function(host, port)

    local uri = " /axis-cgi/jpg/image.cgi"

    local _, status_404, resp_404 = http.identify_404(host,port)

    if status_404 == 200 then

    stdnse.print_debug(1, "%s: Web server returns ambiguous response. Axis webcams return standard 404 status responses. Exiting.", SCRIPT_NAME)



    stdnse.print_debug(1, "%s: HTTP HEAD %s", SCRIPT_NAME,uri)

    local resp = http.head(host, port, uri)

    if resp.status and resp.status == 200 then

    return string.format("Axis video feed is unprotected:http://%s/axis-cgi/jpg/image.cgi ", host.ip)



See the NSE script which contains the exploit for the vulnerable AXIS web camera.

See the screenshot below. We pwned the webserver.


Please ask questions if you have them. Until next time, Good Bye::

I will develop more scripts in the future. You can get the above scripts by the below link:


Become a Certified Ethical Hacker, guaranteed!

Become a Certified Ethical Hacker, guaranteed!

Get training from anywhere to earn your Certified Ethical Hacker (CEH) Certification — backed with an Exam Pass Guarantee.


Revers3r is a Information Security Researcher with considerable experience in Web Application Security, Vulnerability Assessment, Penetration Testing. He is also well-versed in Reverse Engineering, Malware Analysis. He's been a contributor to international magazines like Hakin9, Pentest, and E-Forensics. In his free time, he's contributed to the Response Disclosure Program. website: