Skip to content
ImagineWorld

Reconnaissance and Scanning with Nmap

node_idnode-book_linux-shell-scripting-for-hackers_chapter-04-reconnaissance-and-scanning-with-nmap
node_typechapter-node
schema_profileworld.chapter_node.v1
statusactive
entropyhigh
manifoldworld
domainimagineworld.net
authorityinforms
layercorpus
chapter_num4
chapter_titleReconnaissance and Scanning with Nmap
governed_byCORPUS
constitutional_citationCONSTITUTION
local graph

Chapter 4 — Reconnaissance and Scanning with Nmap

Section titled “Chapter 4 — Reconnaissance and Scanning with Nmap”

Network reconnaissance is a crucial step in identifying potential vulnerabilities and securing networks. This chapter explores the use of Network Mapper (Nmap), a powerful open-source tool, in combination with bash scripting to automate network scanning and vulnerability assessment processes.

We’ll cover various Nmap scan types, including Transmission Control Protocol (TCP) connect scans, Synchronize (SYN) scans, and User Datagram Protocol (UDP) scans, enabling you to efficiently enumerate open ports, detect running services, and fingerprint operating systems across multiple targets. You’ll learn how to leverage bash scripting to execute complex scan sequences, parse and format Nmap output, generate comprehensive reports, and schedule regular scans using cron jobs.

Additionally, we’ll dive into the Nmap Scripting Engine (NSE), a robust feature that extends Nmap’s capabilities through custom scripts.

By the end of this chapter, you’ll have a solid understanding of how to harness the combined power of Nmap and bash scripting.

In this chapter, we are going to cover the following topics:

  • Automate scans with Nmap
  • Parsing, formatting Nmap scan results and creating reports
  • Nmap Scripting Engine for enhanced scans

To follow along in this chapter, you will need the following:

  • Kali Linux
  • Metasploitable 2
  • A code editor of your choice for example, Microsoft Visual Studio Code

If you do not have all these requirements, please read Chapter 2 to get them.

The code for this chapter is available in the book’s GitHub repository.

Nmap (short for Network Mapper) plays a vital role in helping security professionals and network administrators identify potential vulnerabilities and secure their networks. While Nmap is a powerful tool, manually executing scans can be time-consuming and prone to human error, especially in large or complex environments. Automating Nmap scans with bash scripting can improve the process.

Nmap is an open-source utility for network discovery and security auditing. It is widely used by security professionals, network administrators, and ethical hackers to scan networks and systems for open ports, identify running services, detect operating systems, and gather other valuable information about network assets.

Automating Nmap scans with bash scripts offers several benefits:

  • Consistency: Automated scripts ensure that scans are performed consistently, reducing the risk of human error or oversight.
  • Efficiency: Scripting allows you to execute complex scan sequences and cover large networks with minimal manual intervention.
  • Scheduling: Scripts can be scheduled to run at specific intervals, ensuring regular network monitoring and vulnerability assessment.
  • Reproducibility: Documented scripts enable easy reproducibility of scans, facilitating collaboration and knowledge sharing among teams.
  • Scalability: bash scripts can be designed to handle multiple targets, IP ranges, or even entire subnets, making it easier to manage and scan large networks.

Before diving into Nmap automation, it’s essential to understand the different types of scans Nmap supports. Each scan type serves a specific purpose and provides unique information about the target network or system.

The TCP connect scan (-sT) is one of the most basic and reliable scan types. It attempts to establish a full TCP connection with the target system’s open ports, providing accurate information about open, closed, and filtered ports. This scan type is relatively noisy and may be detected by firewalls or intrusion detection systems (IDS).

The SYN scan (-sS), also known as a stealth scan, is a stealthier alternative to the TCP connect scan. It attempts to establish a TCP connection by sending SYN packets and analyzing the responses without completing the full three-way handshake. The three-way handshake is the standard method for establishing a TCP connection, consisting of three steps: SYN (synchronize) from the client, SYN-ACK (synchronize-acknowledge) from the server, and ACK (acknowledge) from the client. The SYN scan only performs the first step and analyzes the response, making it less detectable. This scan type is less likely to be detected by firewalls or IDS, but may not work against certain systems or configurations. Examples of situations where SYN scans may be ineffective include:

  • Stateful firewalls that track connection states and block incomplete handshakes
  • Networks implementing SYN flood protection mechanisms
  • Systems behind proxy servers or network address translation (NAT) devices

The UDP scan (-sU) is used to scan for open UDP ports on target systems. UDP is a connectionless protocol, and this scan type sends UDP packets to the target ports and analyzes the responses to determine whether the ports are open, closed, or filtered.

Nmap offers a wide range of other scan types, including:

  • TCP Null Scan (sN): Sends TCP packets with no flags set, which can sometimes bypass certain firewall rules.
  • FIN Scan (sF): Sends TCP packets with the FIN flag set, another technique that may evade some firewalls.
  • Xmas Scan (sX): Sends TCP packets with FIN, PSH, and URG flags set, creating a “lit up” packet that may trigger different responses from various systems.
  • Idle/Zombie Scan (sI): Uses a third-party idle system to perform a scan, making it harder to trace back to the original scanner.
  • Version Detection Scan (sV): Probes open ports to determine service/version info, crucial for identifying vulnerabilities.
  • Script Scan (-script): Utilizes NSE to run various scripts for advanced information gathering and vulnerability detection.

Each scan type has its own strengths, weaknesses, and use cases, allowing security professionals and network administrators to tailor their scans to specific requirements. To learn more in depth about these scan types, feel free to consult the Nmap documentation, which you can find here: https://nmap.org/book/scan-methods.html

To get started with automating Nmap scans, let’s begin with a basic bash script that performs a TCP connect scan on a target IP range:

#!/bin/bash
# Set the target IP range
target_range="192.168.1.0/24"
# Perform a TCP connect scan
nmap -sT -oN basic_scan.txt $target_range

In this script, we define the target IP range (192.168.1.0/24) and execute the nmap command with the -sT option to perform a TCP connect scan. The -oN option saves the scan output to a file named basic_scan.txt.

While the previous script demonstrates a simple automation, bash scripting shines when incorporating output parsing and formatting. Consider the following script that reads target IP addresses from a file, performs a TCP connect scan and a version detection scan, and formats the output in a tabular format:

#!/bin/bash
# Read the list of target IP addresses from a file
targets_file="targets.txt"
mapfile -t targets < "$targets_file"
# Function to create a table for TCP scan
print_tcp_table() {
# Header for TCP Scan Table
echo "+-----------------+------------+"
echo "| Port | Status |"
echo "+-----------------+------------+"
# Loop through each line of the TCP scan results and format it into a table row
while IFS= read -r line; do
port=$(echo "$line" | awk '{print $1}')
status=$(echo "$line" | awk '{print $2}')
printf "| %-15s | %-10s |\n" "$port" "$status"
done <<< "$1"
# Closing table border
echo "+-----------------+------------+"
}
# Function to create a table for Version Detection scan with a wider version column
print_version_table() {
# Header for Version Detection Table
echo "+-----------------+------------+---------------+------------------------------------------------------------+"
echo "| Port | Status | Protocol | Version |"
echo "+-----------------+------------+---------------+------------------------------------------------------------+"
# Loop through each line of the Version Detection results and format it into a table row
while IFS= read -r line; do
port=$(echo "$line" | awk '{print $1}')
status=$(echo "$line" | awk '{print $2}')
protocol=$(echo "$line" | awk '{print $3}')
version=$(echo "$line" | cut -d' ' -f4-)
# Clean the version by removing any repetition of the status
version_cleaned=$(echo "$version" | sed "s/$status//")
# Adjust table format for a wider protocol and version column
printf "| %-15s | %-10s | %-13s | %-58s |\n" "$port" "$status" "$protocol" "$version_cleaned"
done <<< "$1"
# Closing table border
echo "+-----------------+------------+---------------+------------------------------------------------------------+"
}
# Loop through the list of targets
for target in "${targets[@]}"; do
# Perform a TCP connect scan
tcp_scan=$(nmap -sT -oN - "$target" | grep -E 'open|filtered')
# Perform a version detection scan
version_scan=$(nmap -sV -oN - "$target" | grep -E 'open|filtered')
# Print the target IP address
echo "Target: $target"
# Print the TCP scan results as a table
echo "TCP Connect Scan Results:"
print_tcp_table "$tcp_scan"
# Separator between the two tables
echo "------------------------------------------"
# Print the version detection scan results as a table
echo "Version Detection Scan Results:"
print_version_table "$version_scan"
# Print a separator for better readability between targets
echo "=================================================="
done

In this script, we read the list of target IP addresses from a file named targets.txt using the mapfile command. We then iterate over each target and perform two different types of Nmap scans:

  • TCP connect scan (sT)
  • Version detection scan (sV)

Instead of simply outputting the scan results, we utilize two functions, print_tcp_table and print_version_table, to format the results into structured tables. These functions handle the formatting of the scan results, presenting columns for port numbers, statuses, protocols, and versions in a visually appealing manner.

Here is what the output would look like:

Figure 4.1 – Structured Nmap scan output formatted by a Bash script

Figure 4.1 – Structured Nmap scan output formatted by a Bash script

In the previous examples, we focused on running Nmap scans on demand, but bash scripts can also be used in conjunction with the cron utility to schedule regular scans. Here’s an example of how to set up a cron job to run an Nmap scan every day at midnight:

# Open the crontab editor
crontab -e
# Add the following line to the crontab file
0 0 * * * /opt/scripts/nmap_scan.sh > ~/nmap-logs/scan_output.txt

In this example, we open the crontab editor with crontab -e and add a new line to schedule the execution of the nmap_scan.sh script at midnight (0 0 * * *). The script’s output is redirected to a file named scan_output.txt using the > operator.

Advanced Nmap scripting techniques – parallel scanning

Section titled “Advanced Nmap scripting techniques – parallel scanning”

Nmap supports parallel scanning, which can significantly speed up the scanning process by utilizing multiple threads or processes. bash scripts can leverage this feature to scan large networks or numerous targets simultaneously. Let’s take a look at this example script that performs parallel TCP connect scans on multiple target IP ranges:

#!/bin/bash
# Define the list of target IP ranges
targets=("192.168.1.0/24" "192.168.2.0/24" "192.168.3.0/24")
# Loop through the list of targets
for target in "${targets[@]}"
do
# Perform a parallel TCP connect scan
nmap -sT --max-parallelism 50 -oN "$target"_scan.txt "$target" &
done
# Wait for all scans to complete
wait

In this script, we define an array of target IP ranges (targets). We then use a for loop to iterate over each target and execute a TCP connect scan with the --max-parallelism option set to 50, allowing up to 50 parallel scans to run simultaneously. The & at the end of the nmap command causes the scan to run in the background, allowing the script to continue executing the next iteration.

While parallelism can greatly enhance scanning speed, it’s important to consider its potential downsides. High parallelism levels can cause significant traffic and may overwhelm the target network, leading to performance degradation or even downtime. Always ensure you have proper authorization before scanning a network, and avoid excessive probing that could have unintended consequences.

As a general guideline, the number of parallel threads should be adjusted based on the size and scope of the network. For smaller networks, a lower level of parallelism might be appropriate to minimize disruption, while larger networks may be able to handle higher volumes without adverse effects. Finally, we use the wait command to ensure the script waits for all background scans to complete before exiting.

While Nmap provides valuable information, its output can be extensive and challenging to parse and analyze, especially when dealing with large-scale scans or complex networks. This is where the ability to parse, format, and generate reports from Nmap scan results becomes crucial.

Parsing, formatting Nmap scan results, and creating reports

Section titled “Parsing, formatting Nmap scan results, and creating reports”

By automating the scanning process with bash scripts, we can efficiently analyze scan data and communicate findings in a clear and organized manner.

In addition to automating the process, bash scripts can be used to generate professional-looking reports from the scan results. This can be achieved by parsing the Nmap output and formatting it into a report using various text processing tools like awk, sed, or even custom HTML templates.

Before diving into parsing and formatting Nmap output, it’s essential to understand its structure and different output formats. Nmap provides several output formats, including the default, grepable output, XML output, and script output formats.

The grepable output is a human-readable format that displays scan results in a tabular format, with each line representing a scanned host or port. This output is easy to read but can be challenging to parse programmatically due to its variable structure.

The XML output, on the other hand, is a structured format that follows a well-defined schema, making it easier to parse and process with scripts or other tools. However, the XML output can be verbose and may require additional parsing to extract relevant information.

As mentioned, Nmap does provide various built-in output formats, including the grepable output, XML output, and script output formats. However, there are several reasons why creating custom output or reports using bash scripts can be beneficial:

  • Accessibility: As the default shell on most Unix-based systems (including Linux and macOS), bash is readily available, requiring no additional software installation.
  • Scripting power: bash scripting provides a flexible and powerful way to manipulate text data, making it well-suited for parsing and formatting Nmap output.
  • Integration with command-line tools: bash seamlessly integrates with other command-line utilities, allowing you to leverage tools like sed, awk, and grep for advanced text processing.

Generating custom reports using grep and awk

Section titled “Generating custom reports using grep and awk”

bash provides a range of utilities, such as grep, awk, sed, and cut, which can be used to parse and manipulate Nmap output. Let’s explore an example of generating a custom report using awk:

#!/bin/bash
# Perform nmap scan and store output
nmap_output=$(nmap -oX - -p- -sV 192.168.1.0/24)
# Extract relevant information
open_ports=$(echo "$nmap_output" | xmllint --format - | awk -F'[<>]' '/<port/{print $5}')
services=$(echo "$nmap_output" | xmllint --format - | awk -F'[<>]' '/<service/{print $7}')
# Generate report
echo "Network Scan Report" > report.txt
echo "-------------------" >> report.txt
echo "Date: $(date)" >> report.txt
echo "Network: 192.168.1.0/24" >> report.txt
echo "" >> report.txt
echo "Open Ports and Services:" >> report.txt
paste <(echo "$open_ports") <(echo "$services") | sed 's/\\t/: /' >> report.txt

This script performs an nmap scan on the 192.168.1.0/24 network, extracts the open ports and service information, and generates a simple text report with the scan date, network range, and a list of open ports and services.

Now, let’s explore how we can combine bash with text processing tools to generate a professional-looking custom HTML report from Nmap scan results. We’ll create a script that automates the entire process, from running the scan to producing a formatted report.

First, we set up our scan parameters:

#!/bin/bash
# Set the target IP range
target_range="192.168.1.0/24"
# Perform a TCP connect scan and version detection scan
nmap_output=$(nmap -sT -sV -oN - “$target_range”)

Here, we define the target IP range and execute an Nmap scan. We use the TCP connect (-sT) and version detection (-sV) options to gather comprehensive information. The scan results are stored in the nmap_output variable for further processing.

Next, we begin generating our HTML report:

cat << EOF > report.html
<html>
<head>
<title>Nmap Scan Report</title>
<style>
table, th, td { border: 1px solid black; border-collapse: collapse; padding: 5px; }
</style>
</head>
<body>
<h1>Nmap Scan Report</h1>
<table>
<tr>
<th>IP Address</th>
<th>Port</th>
<th>State</th>
<th>Service</th>
<th>Version</th>
</tr>
EOF

This section creates the structure of our HTML report. We use a here-document (<<EOF) to write the HTML directly to a file named report.html. We include some basic CSS styling to make our table more readable.

The heart of our script lies in processing the Nmap output:

$(echo "$nmap_output" | awk -F'[ /]' '/open/ { printf "<tr><td>%s</td><td>%s</td><td>open</td><td>%s</td><td>%s</td></tr>\\n", $5, $1, $3, $4 }')

This powerful one-liner does the heavy lifting. It pipes the Nmap output to awk, which then:

  • Filters for lines containing ‘open’ ports
  • Splits each line into fields
  • Formats the relevant information into HTML table rows

Finally, we close our HTML tags to complete the report:

</table>
</body>
</html>
EOF

This script demonstrates the power of combining Nmap with bash scripting and text processing tools. In just a few lines of code, we’ve automated the entire process of running a network scan and generating a clear, professional report.

Important note

The complete, unbroken version of this script is available in our GitHub repository for reference and further experimentation.

In the last example, you saw that we manually created an HTML report from an nmap scan. This is because nmap does not provide a built-in option for saving scan results directly as an HTML file. However, it offers a convenient way to convert the XML output to HTML format automatically.

Follow these steps to create nmap HTML reports:

  1. Perform an Nmap scan and save the output as XML.

Run your desired Nmap scan and save the output in XML format using the -oX option:

nmap -oX nmap-scan.xml 192.168.56.1

To ensure the HTML report can be rendered correctly on any web-connected machine, use the --webxml option when running nmap. This option adds a reference to the online version of the nmap.xsl stylesheet hosted on the nmap.org website:

nmap --webxml -oX nmap-scan.xml 192.168.56.1

The XML output will now include the following processing instruction:

<?xml-stylesheet href="<https://nmap.org/svn/docs/nmap.xsl>" type="text/xsl"?>
  1. Convert the XML output to HTML.

Use the xsltproc Extensible Stylesheet Language Transformations (XSLT) processor to convert the Nmap XML output to HTML format:

xsltproc nmap-scan.xml -o nmap-report.html

This command will generate an HTML file (nmap-report.html) containing the Nmap scan results in a visually appealing and interactive format.

The NSE is an incredibly powerful feature of Nmap that allows you to extend its functionality by running scripts during the scan process. These scripts can be used for a wide range of tasks, including advanced host discovery, vulnerability detection, exploitation, and more.

To use NSE scripts with Nmap, you need to include the --script option followed by the script category or individual script name. For example, to run the default set of scripts, you can use the following command:

nmap --script=default [target]

Nmap comes pre-installed with a vast library of NSE scripts categorized by their purpose. You can list all available script categories with the following command:

ls /usr/share/nmap/scripts/

Nmap’s default script category contains a set of scripts that are generally considered safe and useful for most scanning scenarios. In addition to this default category, some other commonly used categories include:

  • auth: Scripts for authentication-related tasks
  • broadcast: Scripts for broadcasting on networks
  • discovery: Scripts for discovering services and information about hosts
  • dos: Scripts that may cause a denial-of-service
  • exploit: Scripts for exploiting vulnerabilities
  • fuzzer: Scripts for fuzzing services
  • intrusive: Scripts that may crash services or cause other undesirable effects
  • malware: Scripts for detecting malware
  • vuln: Scripts for detecting vulnerabilities

Important note

Some script categories, such as dos (denial-of-service) or intrusive, contain scripts that may have more significant impacts on target systems. Always ensure you have proper authorization before using these scripts, especially in production environments.

Incorporating Nmap scripts in a bash script

Section titled “Incorporating Nmap scripts in a bash script”

One of the powerful aspects of NSE is its integration with bash scripting, allowing you to automate and streamline your scanning processes. Here’s an example of a bash script that utilizes NSE to perform a comprehensive network scan:

#!/bin/bash
target_network="192.168.1.0/24"
live_hosts=$(nmap -sn -oG - "$target_network" | awk '/Up/{print $2}')
for host in $live_hosts; do
echo "Scanning $host..."
nmap -sV -p- -oN "$host.nmap" "$host"
nmap --script=vuln "$host" -oN "$host.vuln"
nmap --script=http-enum "$host" -oN "$host.http-enum"
done

In this script, we first set the target network range to scan. Then, we perform a ping scan using Nmap’s -sn option to identify live hosts on the network.

Next, we iterate over each live host and perform the following actions:

  1. Conduct a TCP connect scan using the sV and p- options to identify open ports and services.
  2. Run vulnerability detection scripts from the vuln category using the -script=vuln option.
  3. Run additional NSE scripts as needed, such as the http-enum script for web server enumeration.

The output from each scan is saved to a separate file using the -oN option, allowing for easy review and analysis.

This is just one example of how you can leverage NSE in a bash script. By combining Nmap’s powerful scanning capabilities with the flexibility of NSE scripts and bash scripting, you can automate complex scanning tasks and tailor your scans to your specific needs.

Let’s take a look at another example of incorporating Nmap scripts in a bash script. In this case, we’ll create a script that scans a target network for web servers and checks for potentially vulnerable applications using NSE scripts.

#!/bin/bash
target_network="10.0.0.0/24"
open_ports=$(nmap -sS -oG - "$target_network" | awk '/open/{print $2}')
for host in $open_ports; do
echo "Scanning $host..."
nmap -p80,8080,443 --script=http-title "$host" -oN "$host.web"
nmap -p80,8080,443 --script=http-vuln-cve* "$host" -oN "$host.web-vuln"
done

In this script, we first set the target network range to scan. Then, we perform a TCP SYN scan using Nmap’s -sS option to identify hosts with open ports.

Next, we iterate over each host with open ports and perform the following actions:

  1. Check for web servers on common ports (80, 8080, and 443) using the http-title NSE script, which retrieves the HTML title of the web page.
  2. Run a set of NSE scripts from the http-vuln-cve* category, which detects vulnerabilities in web applications based on known Common Vulnerabilities and Exposures (CVEs).

The output from each scan is saved to separate files using the -oN option, with $host.web containing information about detected web servers, and $host.web-vuln containing information about potential web application vulnerabilities.

This script is particularly useful for identifying and assessing the security posture of web servers and applications on a network. By combining Nmap’s port scanning capabilities with NSE scripts tailored for web application security, you can quickly identify potential vulnerabilities and prioritize remediation efforts.

That’s it for this chapter. Here, we provided an in-depth exploration of automating network reconnaissance and vulnerability scanning using Nmap and bash scripting. You learned how to automate various Nmap scan types, including TCP connect scans and SYN scans. We also covered techniques for parsing and formatting Nmap scan results, as well as generating comprehensive reports through text processing tools like awk and sed. Finally, we looked at NSE, which allows us to automate different scan types.

The next chapter is going to introduce automating web application attacks through various tools and techniques. It will cover web scanning with Nikto and other tools to identify vulnerabilities in web applications. Additionally, you will learn how to automate SQL injection attacks using the powerful SQLMap tool. Finally, we will look at automating OS command injection attacks.

  1. What is the primary advantage of using a SYN scan (-sS) over a TCP connect scan (-sT)?
    1. SYN scans are faster and provide more accurate results 2. SYN scans complete the full three-way handshake, making them more reliable 3. SYN scans are stealthier and less likely to be detected by firewalls or IDS 4. SYN scans work on all systems and configurations without exception
  2. When scheduling Nmap scans using cron jobs, what does the expression 0 0 * * * represent?
    1. Run every hour at the top of the hour 2. Run every day at midnight 3. Run every month on the first day 4. Run every minute
  3. What is the purpose of using the --max-parallelism option in Nmap scans?
    1. To limit the number of ports scanned simultaneously 2. To control how many parallel scans or threads can run at the same time 3. To increase the accuracy of scan results 4. To reduce the memory usage of Nmap
  4. Which Nmap output format is specifically designed to be easier to parse programmatically due to its structured schema?
    1. Grepable output 2. Normal output 3. XML output 4. Script output
  5. What command would you use to convert an Nmap XML output file to an HTML report?
    1. nmap --convert nmap-scan.xml > report.html 2. xmltohtml nmap-scan.xml report.html 3. xsltproc nmap-scan.xml -o nmap-report.html 4. nmap --html nmap-scan.xml report.html
  6. Short answer: Explain why using high levels of parallelism (such as --max-parallelism 50) during network scanning can be problematic, and describe which factors should be considered when determining an appropriate parallelism level for a network scan.
  1. c
  2. b — The cron expression 0 0 * * * schedules a task to run at midnight (0 hours, 0 minutes) every day. The five fields represent minute, hour, day of month, month, and day of week.
  3. b — The --max-parallelism option controls how many parallel scans or threads Nmap can run simultaneously, which can significantly speed up scanning of large networks or multiple targets.
  4. c
  5. c
  6. High parallelism levels can generate significant network traffic that may overwhelm the target network, causing performance degradation, service disruption, or even downtime. Several factors should be considered:
    • Network size and capacity —smaller networks may not handle high traffic volumes well,
      • Authorization and scope —you must have proper permission before scanning,
      • Network stability —production environments require more conservative settings, and
      • Detection concerns —high parallelism creates more noise and increases the likelihood of triggering security alerts.

The parallelism level should be adjusted based on these factors, with lower values for smaller or sensitive networks and higher values only when the network can handle the load without adverse effects.