SCANNING...
// NETWORK SCANNING · HOST DISCOVERY · SERVICE ENUMERATION · NSE SCRIPTING

Nmap Deep
Dive

The most used tool in offensive security — from your first ping sweep to evading firewalls, fingerprinting services, running exploit scripts, and building a detection layer against incoming scans.

LESSON SPLIT — 70% PRACTICAL / 30% THEORY
§1 Setup & Basics §2 Host Discovery §3 Port Scanning §4 Service & OS Detection §5 NSE Scripts §6 Firewall Bypass §7 Defensive Detection §8 Full Recon Lab
NMAP — SECTION OUTLINE 8 SECTIONS · 70% PRACTICAL · OFFENSIVE + BYPASS + DEFENSIVE
SECTYPETOPICWHAT YOU PRACTICEKEY COMMANDS
§1LABSetup & First ScansInstall Nmap, understand the scan workflow, run your first three scans, read output correctly. Understand what each output line means. Set up a safe lab target (Metasploitable/TryHackMe).nmap -v, --open, -oN, -oX
§2OFFENSIVEHost DiscoveryMap an entire subnet without touching ports. ARP scan, ICMP sweep, TCP ping, UDP ping. Discover live hosts silently. Handle networks that block ICMP. Practical: map a /24 network.-sn, -PE, -PS, -PA, -PU, --send-ip
§3OFFENSIVEPort Scanning TechniquesSYN stealth scan, TCP connect, UDP scan, FIN/NULL/XMAS scans. Understand what each returns for open/closed/filtered. Scan all 65535 ports. Control timing from T0 to T5. Practical: full port discovery on target.-sS, -sT, -sU, -sF, -sN, -sX, -p-
§4OFFENSIVEService & OS DetectionBanner grabbing, version detection, OS fingerprinting. Identify exact software versions and patch levels. Build a vulnerability surface from scan results. Practical: fingerprint a target and map to CVEs.-sV, -O, -A, --version-intensity
§5OFFENSIVENSE ScriptsThe Nmap Scripting Engine — run 600+ built-in scripts. Vulnerability detection, authentication bypass, brute-force, exploit checks. Write your own basic NSE script. Practical: run vuln category against target.--script, -sC, vuln, auth, exploit
§6BYPASSFirewall & IDS EvasionFragment packets, spoof source IPs, use decoys, slow scans to avoid rate-limit detection, randomise target order, use zombie idle scanning. Practical: scan a firewalled target without triggering IDS.-f, -D, -S, --source-port, -T0, -sI
§7DEFENSIVEDetecting Nmap ScansWhat Nmap scans look like in Wireshark, Snort, and system logs. Write Snort rules for SYN scan, version scan, and NSE detection. Harden services against fingerprinting. Firewall rule design against scanning.Snort rules, iptables, Wireshark filters
§8LABFull Recon LabComplete offensive recon workflow from zero: host discovery → port scan → service detection → NSE → output parsing → map findings to CVEs → generate professional recon report. TryHackMe/HackTheBox integration.All flags + output formats + grep parsing
01

Setup & First Scans

LAB Install · First Scan · Output Formats · Reading Results · Lab Environment

🎯

Nmap is the first tool every pentester runs on a new target. Before exploiting anything you need to know what's there. Nmap tells you which hosts are alive, which ports are open, what software is running, and what version it is. Everything else in offensive security builds on this foundation.

// §1.1 — INSTALLATION
INSTALL NMAP
# ── KALI LINUX (pre-installed) ────────────────────────────── $ nmap --version Nmap version 7.94 ( https://nmap.org ) $ sudo apt update && sudo apt install nmap -y # update to latest # ── UBUNTU / DEBIAN ───────────────────────────────────────── $ sudo apt install nmap -y # ── TERMUX (Android) ──────────────────────────────────────── $ pkg install nmap -y # ── WINDOWS ────────────────────────────────────────────────── # Download: nmap.org/download.html → nmap-x.xx-setup.exe # Installs WinPcap/Npcap for raw packet access # Use Nmap Zenmap GUI or Command Prompt # ── SET UP A SAFE LAB TARGET ───────────────────────────────── # Option 1: Metasploitable 2 (download from SourceForge, run in VirtualBox) # Option 2: TryHackMe — free rooms with legal scan targets # Option 3: HackTheBox Starting Point machines # Option 4: Use scanme.nmap.org — Nmap's official test server $ nmap scanme.nmap.org # legal scan target provided by Nmap team # ⚠ NEVER scan targets you don't own or have written permission to scan
// §1.2 — YOUR FIRST THREE SCANS
FIRST SCANS — RUN THESE IN ORDER
# SCAN 1: Quick scan — top 1000 ports, no OS or version detection $ nmap 192.168.1.10 Starting Nmap 7.94 ( https://nmap.org ) Nmap scan report for 192.168.1.10 Host is up (0.0023s latency). Not shown: 977 closed tcp ports (reset) PORT STATE SERVICE 22/tcp open ssh 80/tcp open http 443/tcp open https 3306/tcp open mysql # SCAN 2: Verbose — see what Nmap is doing in real time $ nmap -v 192.168.1.10 # Shows: discovered ports as they are found, timing, phases # SCAN 3: Aggressive — version + OS + scripts + traceroute $ nmap -A 192.168.1.10 # Shows: service versions, OS guess, default NSE scripts, route to host # Use this for deep recon after initial port discovery
// §1.3 — READING NMAP OUTPUT
UNDERSTANDING EVERY LINE
OUTPUT LINEWHAT IT MEANSACTION
Host is up (0.002s latency)Target responded to ping/probe — it's aliveProceed with port scan
22/tcp open sshPort 22 is open, running SSHTry banner grab, credential attack, version lookup
80/tcp closed httpPort actively refused — service not runningSkip, note for later
443/tcp filtered httpsFirewall blocking — can't determine stateTry bypass techniques (§6)
Not shown: 977 closed ports977 ports were scanned and closed — not shown to save spaceUse --reason to see why each is closed
OS: Linux 3.x–5.xOS fingerprint match from TCP/IP stack behaviourLook for kernel-specific CVEs
// §1.4 — OUTPUT FORMATS (ALWAYS SAVE YOUR SCANS)
SAVING NMAP OUTPUT
# Normal output — human readable text $ nmap -oN scan.txt 192.168.1.10 # XML output — parseable by other tools (Metasploit imports this) $ nmap -oX scan.xml 192.168.1.10 # Grepable output — easy to parse with grep/awk $ nmap -oG scan.gnmap 192.168.1.10 # ALL formats simultaneously — best practice, always do this $ nmap -oA scan_results 192.168.1.10 # Creates: scan_results.nmap, scan_results.xml, scan_results.gnmap # Parse grepable output — find all open ports $ grep "open" scan.gnmap | awk '{print $2, $5}' # Import XML into Metasploit for automatic exploitation msf> db_import scan.xml msf> hosts # view imported hosts msf> services # view imported services
// §1 LAB EXERCISE
LAB 1 — YOUR FIRST NMAP RECON
  1. Run nmap scanme.nmap.org — note which ports are open and what services they show.
  2. Run the same scan with -v flag — observe the real-time port discovery output.
  3. Run nmap -A scanme.nmap.org -oA lab1_results — save all output formats.
  4. Open lab1_results.nmap in a text editor — read every line and understand what it means using the table above.
  5. Run grep "open" lab1_results.gnmap — extract just the open ports.
  6. Look up the SSH version Nmap found on scanme.nmap.org in cve.mitre.org — are there known vulnerabilities?
// §1 — QUIZ
You run nmap 192.168.1.10 and see filtered next to port 443. You run it again with -sT (TCP connect scan) and still see filtered. What does this tell you and what should you try next?
A Port 443 is closed — filtered and closed mean the same thing
B Try scanning a different port — 443 is always filtered on firewalls
C A firewall is dropping probes — try --source-port 53, -sA ACK scan, or fragmentation to bypass the filter
D Nmap crashed — filtered means the scan failed and you need to restart
02

Host Discovery

OFFENSIVE Subnet Mapping · ARP Scan · ICMP Sweep · TCP Ping · Silent Discovery

🕵️

Before scanning ports you need to know what's alive. Scanning every port on every IP in a /24 network (254 hosts × 65535 ports = 16.6 million port checks) is slow. Host discovery first narrows this to only live hosts — then you port scan just those. Done right, host discovery leaves almost no footprint.

// §2.1 — INTERACTIVE NMAP COMMAND BUILDER

Select options to build your command. Click RUN to see simulated output.

NMAP HOST DISCOVERY BUILDER
DISCOVERY METHOD
TCP/UDP PROBES
OUTPUT & VERBOSITY
TARGET
nmap ← select options above
// §2.2 — HOST DISCOVERY TECHNIQUES COMPARED
TECHNIQUEFLAGHOW IT WORKSBEST FORBLOCKED BY
ARP Scan-PRSends ARP requests — works at layer 2, no IP routing neededLocal LAN — most reliable, cannot be filtered by host firewallNothing on local segment (ARP always works locally)
ICMP Echo-PESends ping (ICMP echo request) to each hostNetworks that allow ping — fast and simpleWindows firewalls block ICMP by default
TCP SYN Ping-PS80,443Sends SYN to port 80/443 — RST or SYN-ACK means host is upNetworks that block ICMP but have web serversStrict firewalls blocking all inbound
TCP ACK Ping-PA80Sends ACK — RST back means host is aliveBypasses some stateful firewalls (ACK not tracked)Stateful firewalls that drop unsolicited ACK
UDP Ping-PU53Sends UDP to closed port — ICMP port unreachable = host aliveNetworks blocking TCP but allowing UDP 53 (DNS)Hosts with firewall blocking ICMP unreachable responses
Skip Ping-PnAssumes all hosts are up, skips discovery phase entirelyWhen you know host is up but blocking all probesWastes time on down hosts
// §2.3 — PRACTICAL: MAPPING A /24 NETWORK
SUBNET DISCOVERY — STEP BY STEP
# ── STEP 1: Fast ARP sweep (local network only) ─────────────── $ sudo nmap -sn -PR 192.168.1.0/24 Starting Nmap 7.94 Host is up (0.00030s latency). 192.168.1.1 (Router) Host is up (0.00051s latency). 192.168.1.10 (Workstation) Host is up (0.00089s latency). 192.168.1.20 (Server) Host is up (0.00124s latency). 192.168.1.50 (Unknown) Nmap done: 254 IP addresses (4 hosts up) scanned in 2.31 seconds # ── STEP 2: Handle ICMP-blocking hosts (TCP ping instead) ──── $ sudo nmap -sn -PS22,80,443,8080 -PA80,443 192.168.1.0/24 # ── STEP 3: No DNS resolution (faster, less noise) ──────────── $ sudo nmap -sn -n -PR 192.168.1.0/24 # ── STEP 4: Save live hosts to file for next step ───────────── $ sudo nmap -sn -PR 192.168.1.0/24 -oG - | grep "Up" | awk '{print $2}' > live_hosts.txt $ cat live_hosts.txt 192.168.1.1 192.168.1.10 192.168.1.20 192.168.1.50 # ── STEP 5: Port scan only live hosts ───────────────────────── $ sudo nmap -iL live_hosts.txt -p- -T4 -oA full_scan # ── PASSIVE host discovery (zero packets sent) ───────────────── $ sudo netdiscover -p -i eth0 # listen only mode — reads existing ARP $ sudo arp-scan -l # ARP scan local network
// §2 LAB EXERCISE
LAB 2 — NETWORK MAPPING
  1. Find your network range: ip addr show — note your IP and subnet mask.
  2. Run ARP discovery: sudo nmap -sn -PR [your_subnet]/24 — list all live hosts.
  3. Save live hosts to file using the grepable output command above.
  4. Try each discovery method (-PE, -PS80, -PA80) — compare which finds more hosts.
  5. On TryHackMe: join "Network Services" room — run host discovery against the provided target IP.
  6. Try discovering a host that has ping blocked: sudo nmap -Pn -sn 192.168.1.1 — does it still respond?
// §2 — QUIZ
You run sudo nmap -sn 192.168.1.0/24 and only find 2 hosts. You know there are at least 10 devices on the network. What is the most likely cause and how do you fix it?
A Wrong subnet — you need to scan a /16 instead of /24
B Most hosts are blocking ICMP ping — use multiple probe types: -PE -PS22,80,443 -PA80 -PU53 to find hosts that block ping
C You need root privileges — run with sudo for host discovery to work
D DNS is blocking the scan — add -n to skip DNS resolution
03

Port Scanning Techniques

OFFENSIVE SYN · TCP Connect · UDP · FIN/NULL/XMAS · Timing · All 65535 Ports

// §3.1 — SCAN TYPE COMPARISON
SCAN TYPEFLAGREQUIRES ROOTHOW IT WORKSLOGGED BY TARGETWHEN TO USE
SYN Stealth-sSYesSends SYN → gets SYN-ACK (open) or RST (closed) → never completes handshakeOften not logged — half-open connectionDefault — fastest and stealthiest
TCP Connect-sTNoFull 3-way handshake → OS handles it via connect() syscallAlways logged — full connection madeWhen you can't use root/raw sockets
UDP Scan-sUYesSends UDP packet → ICMP port unreachable = closed, no response = open|filteredRarely — UDP has no connection conceptFinding DNS, SNMP, TFTP, NTP services
FIN Scan-sFYesSends FIN → closed port sends RST, open port sends nothing (RFC 793)Often bypasses basic IDS — no SYN sentFirewall/IDS evasion (not Windows)
NULL Scan-sNYesSends packet with no TCP flags → same logic as FINVery low — flagless packet looks invalidStealth scanning UNIX systems
XMAS Scan-sXYesSets FIN, PSH, URG flags — "lit up like a Christmas tree"Low on some systemsFirewall evasion on older systems
ACK Scan-sAYesSends ACK → RST from both open and closed ports — maps firewall rules not port statesLowMap which ports a firewall filters
// §3.2 — PRACTICAL: FULL PORT SCANS
PORT SCANNING WORKFLOW — FAST TO THOROUGH
# ── PHASE 1: Fast top-1000 ports (get quick wins) ──────────── $ sudo nmap -sS -T4 192.168.1.10 # Scans 1000 most common ports in ~2 seconds on LAN # ── PHASE 2: All 65535 ports (find hidden services) ────────── $ sudo nmap -sS -p- -T4 192.168.1.10 # -p- means ALL ports (1-65535) # Can take 5-15 minutes depending on timing template # Often finds services on non-standard ports (e.g. SSH on 2222, HTTP on 8080) # ── PHASE 3: UDP scan on key ports ─────────────────────────── $ sudo nmap -sU --top-ports 200 192.168.1.10 # UDP is slow — top 200 ports is a good balance # Look for: 53 (DNS), 161 (SNMP), 123 (NTP), 67 (DHCP), 69 (TFTP) # ── COMBINED: Efficient full recon order ───────────────────── $ sudo nmap -sS -p- --min-rate=5000 -T4 192.168.1.10 -oA ports PORT STATE SERVICE 22/tcp open ssh 80/tcp open http 443/tcp open https 3306/tcp open mysql 8080/tcp open http-proxy 8443/tcp open https-alt 27017/tcp open mongod ← MongoDB on non-standard port! Easy win. # ── Extract just port numbers for next scan ─────────────────── $ grep "open" ports.nmap | awk -F'/' '{print $1}' | tr '\n' ',' 22,80,443,3306,8080,8443,27017, # ── Deep version scan on discovered ports only ──────────────── $ sudo nmap -sV -p 22,80,443,3306,8080,8443,27017 192.168.1.10
// §3.3 — TIMING TEMPLATES
TIMING — T0 TO T5
TEMPLATENAMESPEEDUSE CASEIDS DETECTION RISK
-T0Paranoid5min/portMaximum stealth, IDS evasionVery Low
-T1Sneaky15s/portSlow scan to avoid detectionLow
-T2Polite0.4s/portReduce bandwidth useLow-Medium
-T3NormalDefaultBalanced — default Nmap behaviourMedium
-T4AggressiveFastCTF, lab environments, trusted networksHigh
-T5InsaneVery FastWhen speed matters more than accuracyVery High
// §3 LAB EXERCISE
LAB 3 — PORT SCANNING MASTERY
  1. Run a SYN scan on your Metasploitable VM: sudo nmap -sS -T4 [target_ip] — list every open port.
  2. Run a full port scan: sudo nmap -sS -p- --min-rate=5000 [target_ip] — did you find ports the top-1000 scan missed?
  3. Run a UDP scan: sudo nmap -sU --top-ports 100 [target_ip] — which UDP services are open?
  4. Compare SYN vs TCP connect: run -sS then -sT on the same target — do they find the same ports?
  5. Try a FIN scan: sudo nmap -sF [target_ip] — compare results. Note which ports show different states.
  6. Time comparison: run -T3 vs -T4 on a full port scan — record the time difference with time nmap ...
// §3 — QUIZ
You run sudo nmap -sS -p- 10.10.10.5 and it takes 45 minutes. Your teammate says "just use -T5". Why is that advice wrong for a real penetration test, and what is the better approach?
A Use -T5 — it\'s always better to be fast and accept some missed results
B T5 causes missed ports and always triggers IDS — use --min-rate=1000 with --max-retries=1, or split the range across parallel scans
C Don\'t scan all 65535 ports — only scan the top 1000 to save time
D The scan taking 45 minutes means Nmap is broken — reinstall it
04

Service & OS Detection

OFFENSIVE Banner Grabbing · Version Detection · OS Fingerprinting · CVE Mapping

// §4.1 — VERSION DETECTION IN PRACTICE
SERVICE VERSION DETECTION — REAL OUTPUT
# Version detection (-sV) — probes open ports to determine software + version $ sudo nmap -sV -p 22,80,21,3306 192.168.1.10 PORT STATE SERVICE VERSION 21/tcp open ftp vsftpd 2.3.4 ← BACKDOOR! CVE-2011-2523 22/tcp open ssh OpenSSH 4.7p1 Debian (protocol 2.0) 80/tcp open http Apache httpd 2.2.8 3306/tcp open mysql MySQL 5.0.51a-3ubuntu5 # vsftpd 2.3.4 has a backdoor — smiling face ":)" in username triggers shell # This is a famous vulnerability that gives instant root! # ── Version intensity control ───────────────────────────────── $ nmap -sV --version-intensity 0 192.168.1.10 # light probing $ nmap -sV --version-intensity 9 192.168.1.10 # all probes — most accurate $ nmap -sV --version-all 192.168.1.10 # equivalent to intensity 9 # ── OS Detection (-O) ───────────────────────────────────────── $ sudo nmap -O 192.168.1.10 OS details: Linux 2.6.9 - 2.6.33 Network Distance: 1 hop # ── Aggressive scan (-A) — version + OS + scripts + traceroute $ sudo nmap -A 192.168.1.10 # ── Manual banner grabbing (verify Nmap's findings) ─────────── $ nc -nv 192.168.1.10 21 220 (vsFTPd 2.3.4) ← exact version confirmed from banner $ curl -I http://192.168.1.10 Server: Apache/2.2.8 (Ubuntu) DAV/2
// §4.2 — MAPPING VERSIONS TO CVEs
FROM SCAN OUTPUT TO EXPLOITABLE VULNERABILITIES

Once you have service versions, you search for known vulnerabilities. This is the direct link between Nmap output and exploitation. Every version number Nmap gives you is a search query for CVEs.

SERVICE + VERSION (from Nmap)CVEIMPACTHOW TO EXPLOIT
vsftpd 2.3.4CVE-2011-2523Root RCEUsername with ":)" triggers backdoor on port 6200
OpenSSH 7.2p2CVE-2016-6210User EnumTiming attack reveals valid usernames
Apache 2.2.8CVE-2017-7679RCEmod_mime buffer overflow
MySQL 5.0.51CVE-2016-6662Root RCEConfig file injection leads to root code execution
Samba 3.xCVE-2017-7494 (EternalRed)Root RCEMetasploit exploit/multi/samba/usermap_script
CVE LOOKUP WORKFLOW
# After running nmap -sV, for each service version found: # 1. Search in searchsploit (offline Exploit-DB) $ searchsploit vsftpd 2.3.4 Exploits: vsftpd 2.3.4 - Backdoor Command Execution | unix/remote/17491.rb # 2. Search online resources: # nvd.nist.gov — official CVE database # exploit-db.com — public exploit code # cvedetails.com — CVE browser with filters # 3. Search Metasploit for ready exploits msf> search vsftpd exploit/unix/ftp/vsftpd_234_backdoor excellent VSFTPD v2.3.4 Backdoor Command Execution # 4. Automate with nmap --script vulners (requires vulners NSE script) $ nmap -sV --script vulners 192.168.1.10 | vulners: | vsftpd 2.3.4: | CVE-2011-2523 10.0 https://vulners.com/cve/CVE-2011-2523 | OpenSSH 4.7p1: | CVE-2008-3844 9.3 https://vulners.com/cve/CVE-2008-3844
// §4 LAB EXERCISE
LAB 4 — SERVICE FINGERPRINTING & CVE MAPPING
  1. Run sudo nmap -sV -p- 192.168.1.[metasploitable] — get every service version.
  2. For each service found, run searchsploit [service] [version] — document all matches.
  3. Search nvd.nist.gov for the CVE score of each vulnerability — rank them by CVSS score.
  4. Pick the highest-scoring CVE and find it in Metasploit with search [cve_number].
  5. Run sudo nmap -O 192.168.1.[target] — confirm the OS. Does it match the Metasploitable documentation?
  6. Run nmap -sV --script vulners [target] — compare the automated CVE findings to your manual research.
// §4 — QUIZ
Nmap reports 21/tcp open ftp vsftpd 2.3.4. What is the immediate next step and why is this finding critical?
A Brute force the FTP login with Hydra using a password list
B Immediately check for CVE-2011-2523 — vsftpd 2.3.4 has a planted backdoor that gives instant root shell via Metasploit or manual exploit on port 6200
C Note that FTP is insecure and recommend SFTP — move on to other ports
D Connect with a browser to verify the version manually before doing anything
05

NSE — Nmap Scripting Engine

OFFENSIVE Script Categories · Auth Bypass · Brute Force · Vuln Detection · Custom Scripts

⚙️

NSE turns Nmap from a scanner into an attack platform. 600+ built-in scripts cover everything from banner grabbing to exploiting vulnerabilities. The vuln category alone checks for dozens of critical CVEs automatically. Understanding NSE is what separates a basic scanner from a thorough enumeration engine.

// §5.1 — SCRIPT CATEGORIES
CATEGORYFLAGWHAT IT DOESEXAMPLE SCRIPTS
auth--script authTests authentication — default credentials, bypass methodsftp-anon, http-auth, snmp-brute
vuln--script vulnChecks for known vulnerabilities and CVEsms17-010, smb-vuln-ms08-067, http-shellshock
exploit--script exploitActively exploits vulnerabilitiesUse carefully — actually exploits!
default-sCSafe scripts that run by default — service info, bannersssh-hostkey, http-title, ftp-banner
discovery--script discoveryFind more about the target — DNS, services, sharessmb-enum-shares, dns-zone-transfer
brute--script brutePassword brute forcing across protocolsssh-brute, ftp-brute, http-brute
safe--script safeOnly safe scripts — no risk of crashing servicesAll scripts marked safe in their metadata
// §5.2 — NSE IN PRACTICE
NSE SCRIPTS — PRACTICAL COMMANDS
# ── Run default scripts (-sC equivalent) ───────────────────── $ sudo nmap -sC -sV 192.168.1.10 # ── Run vuln category — check for known CVEs ────────────────── $ sudo nmap --script vuln 192.168.1.10 | smb-vuln-ms17-010: | VULNERABLE: EternalBlue | State: VULNERABLE | Risk factor: HIGH | CVE: CVE-2017-0143 | Description: Remote Code Execution via SMBv1 # ── Check for anonymous FTP access ──────────────────────────── $ nmap --script ftp-anon -p 21 192.168.1.10 | ftp-anon: Anonymous FTP login allowed (FTP code 230) | -rw-r--r-- 1 0 0 104857600 Jan 15 backup.tar.gz # ── SMB enumeration (shares, users, OS) ─────────────────────── $ nmap --script smb-enum-shares,smb-enum-users,smb-os-discovery -p 445 192.168.1.10 | smb-enum-shares: | \\192.168.1.10\ADMIN$ READ, WRITE (current user has write access!) | \\192.168.1.10\C$ READ, WRITE | \\192.168.1.10\secret READ | smb-enum-users: | john.smith, administrator, svc_backup # ── HTTP enumeration ─────────────────────────────────────────── $ nmap --script http-title,http-methods,http-robots.txt,http-headers -p 80,443 192.168.1.10 | http-title: Admin Panel — Login | http-methods: GET POST PUT DELETE OPTIONS ← PUT/DELETE enabled = dangerous! | http-robots.txt: /admin /backup /config # ── SSH host key and algorithms ─────────────────────────────── $ nmap --script ssh-hostkey,ssh2-enum-algos -p 22 192.168.1.10 # ── MySQL enumeration ───────────────────────────────────────── $ nmap --script mysql-info,mysql-databases,mysql-empty-password -p 3306 192.168.1.10 | mysql-empty-password: root account has no password! # ── Heartbleed (OpenSSL vulnerability) ──────────────────────── $ nmap --script ssl-heartbleed -p 443 192.168.1.10 # ── EternalBlue check (MS17-010) ────────────────────────────── $ nmap --script smb-vuln-ms17-010 -p 445 192.168.1.10 # ── Shellshock check ────────────────────────────────────────── $ nmap --script http-shellshock --script-args uri=/cgi-bin/test.sh -p 80 192.168.1.10 # ── List all scripts in a category ──────────────────────────── $ ls /usr/share/nmap/scripts/ | grep smb $ nmap --script-help vuln # detailed info on vuln category
// §5.3 — WRITING A BASIC NSE SCRIPT
CUSTOM NSE SCRIPT — BANNER GRABBER
-- File: /usr/share/nmap/scripts/custom-banner.nse -- Run: nmap --script custom-banner -p 80 target description = [[ Grabs the HTTP server banner and checks for version disclosure. ]] categories = {"default", "safe", "discovery"} local http = require "http" local shortport = require "shortport" -- Only run on HTTP ports portrule = shortport.port_or_service({80, 8080, 443}, "http") action = function(host, port) local response = http.get(host, port, "/") if response and response.header then local server = response.header["server"] if server then return "Server: " .. server end end return "No Server header found" end # Save the file, then run it: $ sudo nmap --script custom-banner -p 80 192.168.1.10 | custom-banner: |_ Server: Apache/2.2.8 (Ubuntu)
// §5 LAB EXERCISE
LAB 5 — NSE SCRIPTING ATTACK CHAIN
  1. Run sudo nmap --script vuln 192.168.1.[metasploitable] — document every vulnerability found.
  2. Run nmap --script ftp-anon -p 21 [target] — can you log in anonymously? If yes, what files are there?
  3. Run nmap --script smb-enum-shares,smb-enum-users -p 445 [target] — what shares and users are visible?
  4. Run nmap --script mysql-empty-password -p 3306 [target] — does root have no password?
  5. Run nmap -sC -sV -p- [target] -oA nse_full — save the complete enumeration.
  6. Write a summary of the attack surface: list every finding and rank by exploitability.
// §5 — QUIZ
You run nmap --script smb-vuln-ms17-010 -p 445 10.10.10.40 and get: VULNERABLE: EternalBlue — Risk factor: HIGH — CVE-2017-0143. What does this mean and what is your exploitation path?
A The target has SQL injection — exploit it with sqlmap
B The machine is vulnerable to EternalBlue — use Metasploit exploit/windows/smb/ms17_010_eternalblue for an unauthenticated SYSTEM shell
C The NSE script result is unreliable — always verify manually before trusting vuln scripts
D The vulnerability only leaks data — it cannot be used for remote code execution
06

Firewall & IDS Evasion

BYPASS Fragmentation · Decoys · Source Port Spoofing · Idle Scan · Slow Scan

👻

A firewall showing "filtered" is not the end — it is the beginning. Every firewall has rules, and rules have gaps. Fragmentation exploits packet reassembly. Decoys hide your real IP among fake ones. Source port spoofing exploits firewall rules that trust certain ports. Idle scanning hides behind a zombie host completely.

// §6.1 — EVASION TECHNIQUES
FIREWALL BYPASS — ALL TECHNIQUES
# ── 1. PACKET FRAGMENTATION ────────────────────────────────── # Splits TCP header across multiple small packets # Some IDS/firewalls don't reassemble — miss the full pattern $ sudo nmap -f 192.168.1.10 # 8-byte fragments $ sudo nmap -f -f 192.168.1.10 # 16-byte fragments $ sudo nmap --mtu 24 192.168.1.10 # custom fragment size (must be multiple of 8) # ── 2. DECOY SCANNING ───────────────────────────────────────── # Makes your scan appear to come from multiple IPs simultaneously # Target sees scans from decoys + your real IP — hard to identify you $ sudo nmap -D 10.0.0.1,10.0.0.2,10.0.0.3,ME 192.168.1.10 # ME = insert your real IP at this position in the decoy list $ sudo nmap -D RND:10 192.168.1.10 # 10 random decoy IPs # Warning: decoy IPs should be UP or target gets flooded with RSTs from down IPs # ── 3. SOURCE PORT SPOOFING ─────────────────────────────────── # Some firewalls allow traffic from port 53 (DNS) or 80 (HTTP) implicitly # Using those as source ports can bypass naive firewall rules $ sudo nmap --source-port 53 192.168.1.10 # use DNS port as source $ sudo nmap --source-port 80 192.168.1.10 # use HTTP port as source $ sudo nmap -g 53 192.168.1.10 # -g is shorthand for --source-port # ── 4. IDLE / ZOMBIE SCAN ───────────────────────────────────── # Uses a third "zombie" host to scan the target # Your IP never appears in target logs — completely invisible # Zombie must be: idle (no traffic), have predictable IP ID sequence $ sudo nmap -sI [zombie_ip] [target_ip] $ sudo nmap -sI 192.168.1.100 192.168.1.10 -p 80,443,22 # First: find a suitable zombie (old Windows/printer with incremental IP ID) # Check: nmap -O --script ipidseq [potential_zombie] — look for "Incremental" # ── 5. SLOW SCAN (timing evasion) ──────────────────────────── # IDS uses rate thresholds — scan slowly enough to stay below them $ sudo nmap -T0 --scan-delay 5s 192.168.1.10 # 5 second delay between probes $ sudo nmap --max-rate 1 192.168.1.10 # max 1 packet per second # ── 6. RANDOMISE TARGET ORDER ────────────────────────────────── $ sudo nmap --randomize-hosts 192.168.1.0/24 # Doesn't scan sequentially — harder for IDS to correlate into a "scan pattern" # ── 7. APPEND RANDOM DATA ────────────────────────────────────── $ sudo nmap --data-length 25 192.168.1.10 # Adds random 25 bytes to packets — changes packet size signatures # ── 8. IPv6 (bypass IPv4 firewalls) ────────────────────────── $ nmap -6 2001:db8::1 # Many orgs have IPv4 firewalls but open IPv6 — check both! # ── COMBINED STEALTH SCAN ───────────────────────────────────── $ sudo nmap -sS -f -D RND:5 --source-port 53 --randomize-hosts \ --data-length 15 -T1 192.168.1.10 # Fragmented + decoys + source port 53 + random data + slow timing # Maximum evasion — use when stealth is critical
// §6.2 — ACK SCAN FOR FIREWALL MAPPING
MAP FIREWALL RULES WITH ACK SCAN
# ACK scan (-sA) maps which ports a FIREWALL is filtering # Unlike other scans it doesn't find open/closed — just FILTERED vs UNFILTERED # Both open and closed ports return RST to ACK → both show as "unfiltered" # If firewall drops the ACK → "filtered" $ sudo nmap -sA -p 1-1000 192.168.1.10 PORT STATE SERVICE 22/tcp unfiltered ssh ← firewall allows ACK to port 22 80/tcp unfiltered http ← firewall allows ACK to port 80 443/tcp filtered https ← firewall DROPS ACK to port 443 (stateful rule) 3306/tcp filtered mysql ← firewall DROPS ACK to MySQL # Interpretation: # unfiltered = firewall passes this traffic (can try actual exploitation) # filtered = stateful firewall tracking connections (port may still be open) # This tells you the FIREWALL TOPOLOGY, not service state # Follow up: on unfiltered ports, use source-port matching the allowed port $ sudo nmap --source-port 80 -p 3306 192.168.1.10 # If firewall allows src:80→any, MySQL might now show as open!
// §6 LAB EXERCISE
LAB 6 — FIREWALL BYPASS PRACTICE
  1. On your firewall (iptables): block port 80 inbound: sudo iptables -A INPUT -p tcp --dport 80 -j DROP
  2. Verify it's filtered: run nmap -p 80 localhost — confirm it shows filtered.
  3. Try bypassing with source port: sudo nmap --source-port 53 -p 80 localhost — does it bypass?
  4. Try fragmentation: sudo nmap -f -p 80 localhost — any difference?
  5. Run an ACK scan: sudo nmap -sA -p 1-100 localhost — which ports show as filtered vs unfiltered?
  6. Add a more specific iptables rule that blocks source port 53 too. Then test what still works.
  7. Clean up: sudo iptables -F to flush all rules when done.
// §6 — QUIZ
You use sudo nmap -sI zombie_host target_host -p 80 (idle scan). The zombie host's IP ID goes from 1000 to 1002 (increments by 2) after your scan. What does this tell you about port 80 on the target?
A Port 80 is closed — the IP ID increment of 2 shows a rejection
B Port 80 is OPEN — increment of 2 means the target sent SYN-ACK to the zombie (open port response) causing zombie to RST, consuming an extra IP ID
C The zombie is not suitable — IP ID incrementing by 2 means it has random IP IDs
D Port 80 is filtered — the firewall intercepted the packet
07

Detecting Nmap Scans

DEFENSIVE Wireshark Signatures · Snort Rules · System Logs · Hardening Against Scanning

🛡️

Every Nmap scan leaves a signature. SYN scans generate thousands of half-open connections. Version detection sends distinctive service probes. NSE scripts have recognisable payloads. Knowing what each scan looks like from the defender's side makes you better at both attacking (avoid detection) and defending (build detection rules).

// §7.1 — WHAT NMAP LOOKS LIKE IN WIRESHARK
SCAN TYPEWIRESHARK FILTERSIGNATURE PATTERN
SYN Scan (-sS)tcp.flags.syn==1 && tcp.flags.ack==0Many SYN packets from one IP to sequential ports in rapid succession. No completing ACK after SYN-ACK.
TCP Connect (-sT)tcp.flags==0x002Full 3-way handshakes followed immediately by RST. Many connections, each lasting milliseconds.
UDP Scan (-sU)udp && icmp.type==3ICMP port unreachable messages flooding back from target — one per closed UDP port.
FIN/NULL/XMAStcp.flags==0x001 || tcp.flags==0x000 || tcp.flags==0x029Packets with unusual flag combinations — FIN without prior SYN, NULL (no flags), or FIN+PSH+URG together.
Version Scan (-sV)tcp && frame.len > 100 && ip.src==[scanner]Service-specific probe strings sent to open ports. Distinctive payload content per protocol.
NSE Scriptshttp.user_agent contains "Nmap"HTTP requests with Nmap user-agent, SMB probe sequences, protocol-specific NSE payloads.
OS Detection (-O)tcp.window_size==1 || tcp.window_size==2Unusual TCP window sizes (1, 2, 4, 63) — Nmap OS probes use specific window values for fingerprinting.
// §7.2 — SNORT RULES FOR NMAP DETECTION
SNORT RULES — DETECT NMAP SCANNING
# ── Detect SYN port scan ───────────────────────────────────── alert tcp any any -> $HOME_NET any ( msg:"NMAP SYN Port Scan Detected"; flags:S; threshold: type both, track by_src, count 30, seconds 5; classtype:network-scan; sid:1000201; rev:1; ) # Fires when any source sends 30+ SYN packets in 5 seconds # ── Detect FIN scan ─────────────────────────────────────────── alert tcp any any -> $HOME_NET any ( msg:"NMAP FIN Scan Detected"; flags:F,!SAPRU; classtype:network-scan; sid:1000202; rev:1; ) # FIN packet without prior SYN = stealth scan attempt # ── Detect NULL scan ────────────────────────────────────────── alert tcp any any -> $HOME_NET any ( msg:"NMAP NULL Scan Detected"; flags:0; classtype:network-scan; sid:1000203; rev:1; ) # ── Detect XMAS scan ────────────────────────────────────────── alert tcp any any -> $HOME_NET any ( msg:"NMAP XMAS Scan Detected"; flags:FPU; classtype:network-scan; sid:1000204; rev:1; ) # ── Detect Nmap version scan (HTTP probe) ───────────────────── alert tcp any any -> $HOME_NET 80 ( msg:"NMAP HTTP Version Scan"; content:"User-Agent|3a| Nmap"; nocase; http_header; classtype:network-scan; sid:1000205; rev:1; ) # ── Detect OS detection probes (window size 1) ──────────────── alert tcp any any -> $HOME_NET any ( msg:"NMAP OS Detection Probe - Window Size 1"; flags:S; window:1; classtype:network-scan; sid:1000206; rev:1; ) # ── Detect NSE SMB enumeration ──────────────────────────────── alert tcp any any -> $HOME_NET 445 ( msg:"NMAP SMB Enumeration Script"; content:"|ff|SMB"; depth:4; offset:4; threshold: type both, track by_src, count 5, seconds 10; classtype:network-scan; sid:1000207; rev:1; )
// §7.3 — SYSTEM LOG ANALYSIS FOR SCANS
DETECTING SCANS IN SYSTEM LOGS
# ── Linux syslog / auth.log ─────────────────────────────────── # SSH brute force from nmap ssh-brute script: $ grep "Failed password" /var/log/auth.log | awk '{print $11}' | sort | uniq -c | sort -rn 847 192.168.1.50 ← NSE ssh-brute script running against us # ── iptables logging — log all dropped packets ──────────────── $ sudo iptables -A INPUT -j LOG --log-prefix "DROPPED: " --log-level 4 $ sudo tail -f /var/log/kern.log | grep "DROPPED" DROPPED: IN=eth0 SRC=192.168.1.50 DST=192.168.1.10 PROTO=TCP DPT=22 FLAGS=S DROPPED: IN=eth0 SRC=192.168.1.50 DST=192.168.1.10 PROTO=TCP DPT=23 FLAGS=S DROPPED: IN=eth0 SRC=192.168.1.50 DST=192.168.1.10 PROTO=TCP DPT=25 FLAGS=S # Sequential port scan visible in kernel log # ── Automated detection with fail2ban ───────────────────────── # /etc/fail2ban/filter.d/portscan.conf: failregex = DROPPED.*SRC= # /etc/fail2ban/jail.conf: [portscan] enabled = true filter = portscan logpath = /var/log/kern.log maxretry = 50 findtime = 10 bantime = 3600 # Automatically bans any IP that triggers 50+ drops in 10 seconds # ── Splunk SPL for Nmap detection ───────────────────────────── index=network_logs tcp_flags="S" | stats dc(dest_port) as unique_ports count by src_ip | where unique_ports > 50 | sort -unique_ports # Any IP hitting 50+ unique destination ports = likely port scan
// §7.4 — HARDENING AGAINST SCANNING
REDUCE SCAN FOOTPRINT
  • Remove or change default service banners — ServerTokens Prod in Apache (hides version)
  • Disable unnecessary services — every closed port is one less attack surface
  • Change default ports — SSH on 2222 instead of 22 reduces automated scan hits (security through obscurity only)
  • Use --version-intensity 0 equivalent on services — disable verbose error messages
  • Block ICMP echo with iptables — forces Nmap to use TCP ping (slower, noisier for attacker)
DETECT & RESPOND
  • Deploy psad (Port Scan Attack Detector) — reads iptables logs and auto-blocks scanners
  • Enable Suricata in IPS mode — automatically drops connections matching scan signatures
  • Use honeypot ports — open a fake port (e.g. 8888) with no service. Any connection = scanner/attacker
  • Monitor /var/log/auth.log with fail2ban for SSH scanning
  • Set up Zeek on your network tap — produces automatic scan detection notices in notice.log
// §7 — QUIZ
Your Snort alert fires on "SYN Scan Detected" from 192.168.1.50 at 02:14 AM. You check the logs and see 3,847 SYN packets in 12 seconds across ports 1-65535. The IP belongs to your internal network. What is your immediate response and what follow-up investigation do you do?
A Ignore it — internal IPs scanning the network is normal for IT teams doing vulnerability assessments
B Verify if 192.168.1.50 is an authorised scanner — if not, isolate immediately and investigate for compromise (malware often scans internally before lateral movement)
C Block 192.168.1.50 at the firewall and close the ticket
D It must be a security tool — only escalate if it\'s from an external IP
08

Full Recon Lab

LAB Complete Workflow · Output Parsing · CVE Mapping · Professional Report

🎓

This is the capstone — put everything together. Real pentesters run a methodical recon workflow, not random commands. Every tool, flag, and technique from §1–§7 feeds into a structured process that ends with a prioritised list of vulnerabilities ready for exploitation.

// §8.1 — COMPLETE RECON WORKFLOW
PROFESSIONAL NMAP RECON — FULL WORKFLOW
############################################################## # PHASE 0: SETUP ############################################################## $ mkdir -p recon/{nmap,screenshots,notes} $ TARGET="192.168.1.10" $ echo "Target: $TARGET" >> recon/notes/recon.txt ############################################################## # PHASE 1: HOST DISCOVERY (confirm target is alive) ############################################################## $ sudo nmap -sn -PR -PE -PS22,80,443 $TARGET -oN recon/nmap/host_discovery.txt Host is up (0.0021s latency). ✓ ############################################################## # PHASE 2: FAST PORT SCAN (top 1000 ports — quick overview) ############################################################## $ sudo nmap -sS -T4 $TARGET -oA recon/nmap/fast_scan # Read output immediately — note all open ports ############################################################## # PHASE 3: FULL PORT SCAN (all 65535 — find hidden services) ############################################################## $ sudo nmap -sS -p- --min-rate=5000 $TARGET -oA recon/nmap/full_ports # Extract open ports: $ PORTS=$(grep "open" recon/nmap/full_ports.nmap | awk -F'/' '{print $1}' | tr '\n' ',' | sed 's/,$//') $ echo "Open ports: $PORTS" ############################################################## # PHASE 4: VERSION + OS DETECTION (on discovered ports) ############################################################## $ sudo nmap -sV -sC -O -p $PORTS $TARGET -oA recon/nmap/versions ############################################################## # PHASE 5: UDP SCAN (often missed services) ############################################################## $ sudo nmap -sU --top-ports 200 $TARGET -oA recon/nmap/udp_scan ############################################################## # PHASE 6: NSE VULNERABILITY SCRIPTS ############################################################## $ sudo nmap --script vuln -p $PORTS $TARGET -oA recon/nmap/vuln_scan $ sudo nmap --script auth -p $PORTS $TARGET -oA recon/nmap/auth_scan $ sudo nmap --script discovery -p $PORTS $TARGET -oA recon/nmap/discovery ############################################################## # PHASE 7: PARSE AND SUMMARISE ############################################################## $ echo "=== OPEN PORTS ===" && grep "open" recon/nmap/full_ports.nmap $ echo "=== VULNERABILITIES ===" && grep "VULNERABLE\|CVE\|CRITICAL" recon/nmap/vuln_scan.nmap $ echo "=== AUTH ISSUES ===" && grep "allowed\|anonymous\|empty" recon/nmap/auth_scan.nmap ############################################################## # PHASE 8: IMPORT TO METASPLOIT ############################################################## msf> workspace -a target_recon msf> db_import recon/nmap/versions.xml msf> vulns # view imported vulnerabilities msf> hosts # view discovered hosts
// §8.2 — SAMPLE FULL RECON OUTPUT (METASPLOITABLE)
Starting Nmap 7.94 — Full Recon of 192.168.1.10 (Metasploitable 2) ═══════════════════════════════════════════════════════════════ PORT STATE SERVICE VERSION 21/tcp open ftp vsftpd 2.3.4 | ftp-anon: Anonymous FTP login allowed | ftp-vsftpd-backdoor: VULNERABLE (CVE-2011-2523) ← INSTANT ROOT 22/tcp open ssh OpenSSH 4.7p1 23/tcp open telnet Linux telnetd | TELNET: Plaintext protocol — credentials in clear text 25/tcp open smtp Postfix smtpd 80/tcp open http Apache httpd 2.2.8 | http-vuln-cve2017-5638: VULNERABLE (Apache Struts RCE) 139/tcp open netbios-ssn Samba smbd 3.x 445/tcp open netbios-ssn Samba smbd 3.0.20 | smb-vuln-cve2009-3103: VULNERABLE ← Samba Command Injection | smb-enum-shares: ADMIN$ C$ tmp (READ/WRITE access!) 3306/tcp open mysql MySQL 5.0.51a | mysql-empty-password: root account has EMPTY PASSWORD 5432/tcp open postgresql PostgreSQL 8.3.0 6667/tcp open irc UnrealIRCd | irc-unrealircd-backdoor: VULNERABLE (CVE-2010-2075) ← Another backdoor! 8180/tcp open http Apache Tomcat 5.5 | http-default-accounts: Tomcat manager default creds work! (tomcat:tomcat) OS: Linux 2.6.9 - 2.6.33 ═══════════════════════════════════════════════════════════════ CRITICAL FINDINGS (exploit immediately): [10.0] vsftpd 2.3.4 backdoor → instant root via MSF [10.0] UnrealIRCd backdoor → instant root via MSF [9.8] MySQL root empty password → full DB access [9.0] SMB command injection → remote code execution [8.5] Tomcat default creds → war file upload → shell
// §8.3 — PROFESSIONAL RECON REPORT STRUCTURE
WHAT TO DOCUMENT AFTER EVERY NMAP RUN
SECTIONCONTENTEXAMPLE
Target SummaryIP, hostname, OS, scan date/time192.168.1.10 (Metasploitable) — Linux 2.6.x — Scanned 2024-01-15 14:30
Open PortsAll open ports with service and version21/tcp vsftpd 2.3.4, 22/tcp OpenSSH 4.7p1 ...
Critical FindingsCVSS 9.0+ vulnerabilities with CVECVE-2011-2523: vsftpd backdoor — CVSS 10.0 — Unauthenticated RCE
High FindingsCVSS 7.0-8.9 vulnerabilitiesCVE-2017-5638: Apache Struts — CVSS 8.5 — RCE via Content-Type
Attack SurfaceRanked exploitation paths1. vsftpd backdoor (instant root) 2. IRC backdoor 3. MySQL no password ...
RecommendationsPatch/mitigate each findingUpdate vsftpd to 2.3.5+, disable telnet, set MySQL root password ...
// §8 FINAL LAB EXERCISE
FINAL LAB — COMPLETE PENTEST RECON ON METASPLOITABLE
  1. Run the complete Phase 0–8 workflow above against your Metasploitable VM. Save all output.
  2. List every open port and service version found. Check each one in searchsploit.
  3. Rank all vulnerabilities by CVSS score. Identify the top 3 easiest exploitation paths.
  4. Exploit the vsftpd backdoor using Metasploit. Confirm you get a root shell. use exploit/unix/ftp/vsftpd_234_backdoor
  5. Write a one-page recon report using the structure above. Include: target summary, all open ports, critical findings with CVE numbers, and recommended exploitation path.
  6. Bonus: Enable iptables logging on Metasploitable, run your scan, then check the logs — what does your scan look like from the defender's perspective?
  7. TryHackMe: Complete "Blue" room using only Nmap for recon — no hints. EternalBlue is the path.
// §8 FINAL QUIZ
You run a full Nmap recon on a target and find: port 22 (OpenSSH 7.4), port 80 (nginx 1.10.3), port 8080 (Apache Tomcat 7.0.88), port 3306 (MySQL 5.7.22) only accessible from localhost, and port 27017 (MongoDB 3.4.0) with no authentication. Rank these by exploitation priority and explain your reasoning.
A SSH first — it gives the most direct access to the system
B Port 80 first — web servers always have the most vulnerabilities
C Priority: (1) MongoDB no-auth = instant full database access, (2) Tomcat default creds → WAR shell, (3) nginx web vulns, (4) MySQL only after getting RCE, (5) SSH last
D MySQL first — databases always contain the most valuable data
NMAP DEEP DIVE — COMPLETE

You can now map networks, enumerate services, detect OS and versions, run vulnerability scripts, evade firewalls, and build detection rules against your own scans.

8
SECTIONS
8
QUIZZES
30+
LAB TASKS
7
SNORT RULES
70%
PRACTICAL