Penetration testing

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

Revers3r
May 6, 2015 by
Revers3r

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:

Earn two pentesting certifications at once!

Earn two pentesting certifications at once!

Enroll in one boot camp to earn both your Certified Ethical Hacker (CEH) and CompTIA PenTest+ certifications — backed with an Exam Pass Guarantee.

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 192.168.195.130

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 192.168.195.130

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 192.168.195.130

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 192.168.195.130

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.

http://www.cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2012-2122

http://www.exploit-db.com/exploits/19092/

http://blog.trendmicro.com/trendlabs-security-intelligence/mysql-password-verification-bypass-cve-2012-2122/

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 google.com

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 http://nmap.org/book/man-legal.html"

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"}

Rules

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:

prerule()

hostrule(host)

portrule(host, port)

postrule()

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.

Action

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 http://nmap.org/book/nse-api.html#nse-structured-output.

Environment Variables

Each script has its own set of environment variables:

SCRIPT_PATH

Describes The script path.

SCRIPT_NAME

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

SCRIPT_TYPE

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.

afp

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

ajp

A basic AJP 1.3 implementation based on documentation available from Apache mod_proxy_ajp; http://httpd.apache.org/docs/2.2/mod/mod_proxy_ajp.html

amqp

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

asn1

ASN.1 functions.

base32

Base32 encoding and decoding. Follows RFC 4648.

base64

Base64 encoding and decoding. Follows RFC 4648.

bin

Pack and unpack binary data.

bit

Bitwise operations on integers.

bitcoin

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

bittorrent

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.

bjnp

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

brute

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

cassandra

Library methods for handling Cassandra Thrift communication as a client.

citrixxml

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.

comm

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

creds

The credential class stores found credentials in the Nmap registry.

cvs

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

datafiles

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

dhcp

Implement a Dynamic Host Configuration Protocol (DHCP) client.

For more libraries we can follow the below links:

http://nmap.org/book/nse-library.html

http://nmap.org/nsedoc/

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.

host

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

host.os

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

[plain]

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"

"cpe:/<...>",

[More CPE]

}

},

[More classes]

},

},

[More OS matches]

}

[/plain]

Similarl to host.os are different sub component available for Nmap API like host.ip, host.name, host.region etc. For full components we can follow the link here: http://nmap.org/book/nse-api.html.

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:

require("nmap")

local socket = nmap.new_socket()

socket:set_timeout(1000)

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

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

try(socket:send("login"))

response = try(socket:receive())

socket:close()

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()

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))

OUR FIRST NSE SCRIPT:

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 (http://nmap.org/book/nse-tutorial.html).

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)

    return

    end

    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)

    end

    end

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

See the screenshot below. We pwned the webserver.

Pwned……………..

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:

https://github.com/bikashdash/Axis_Vuln_Webcam

References

https://secwiki.org/w/Nmap/External_Script_Library

FREE role-guided training plans

FREE role-guided training plans

Get 12 cybersecurity training plans — one for each of the most common roles requested by employers.

http://nmap.org/book/nse-tutorial.html

Revers3r
Revers3r

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: www.vulnerableghost.com