Port Scanning Techniques | Nmap Network Scanning (2024)

  • Nmap Network Scanning
  • Chapter15.Nmap Reference Guide
  • Port Scanning Techniques

Port Scanning Techniques

As a novice performing automotive repair, I can strugglefor hours trying to fit my rudimentary tools (hammer, duct tape,wrench, etc.) to the task at hand. When I fail miserably and tow myjalopy to a real mechanic, he invariably fishes around in a huge tool chest untilpulling out the perfect gizmo which makes the job seem effortless. Theart of port scanning is similar. Experts understand the dozens ofscan techniques and choose the appropriate one (or combination) for agiven task. Inexperienced users andscript kiddies,on the otherhand, try to solve every problem with the default SYN scan. Since Nmap isfree, the only barrier to port scanning mastery is knowledge. Thatcertainly beats the automotive world, where it may take great skill todetermine that you need a strut spring compressor, then you stillhave to pay thousands of dollars for it.

Most of the scan types are only available toprivileged users.This is because they send and receiveraw packets,which requires rootaccess on Unix systems. Using an administrator account on Windows isrecommended, though Nmap sometimes works for unprivileged users on thatplatform when Npcap has already been loaded into the OS. Requiringroot privileges was a serious limitation when Nmap was released in1997, as many users only had access to shared shell accounts. Now,the world is different. Computers are cheaper, far more people havealways-on direct Internet access, and desktop Unix systems (includingLinux and Mac OS X) are prevalent. A Windows version of Nmap is nowavailable, allowing it to run on even more desktops. For all thesereasons, users have less need to run Nmap from limited shared shell accounts.This is fortunate, as the privileged options make Nmap far morepowerful and flexible.

While Nmap attempts to produce accurate results, keep in mindthat all of its insights are based on packets returned by the targetmachines (or firewalls in front of them). Such hosts may beuntrustworthy and send responses intended to confuse or mislead Nmap.Much more common are non-RFC-compliant hosts that do not respond asthey should to Nmap probes. FIN, NULL, and Xmas scans areparticularly susceptible to this problem. Such issues are specific tocertain scan types and so arediscussed in the individual scan type entries.

This section documents the dozen or so port scantechniques supported by Nmap. Only one method may be used at a time,except that UDP scan (-sU) and any one of theSCTP scan types (-sY, -sZ)may be combined with any one of the TCP scan types.As a memory aid, port scan type optionsare of the form -s<C>, where<C> is a prominent character in the scanname, usually the first. The one exception to this is the deprecatedFTP bounce scan (-b). By default, Nmap performs aSYN Scan, though it substitutes a connect scan if the user does nothave proper privileges to send raw packets (requires root access onUnix). Of the scans listed in thissection, unprivileged users can only execute connect and FTP bouncescans.

-sS (TCP SYN scan)

SYN scan is the default and most popular scan option for goodreasons. It can be performed quickly, scanning thousands of ports persecond on a fast network not hampered by restrictive firewalls. It is alsorelatively unobtrusive and stealthy since it never completes TCPconnections. SYN scan works against any compliant TCP stack ratherthan depending on idiosyncrasies of specific platforms as Nmap'sFIN/NULL/Xmas, Maimon and idle scans do. It also allows clear,reliable differentiation between the open,closed, and filteredstates.

This technique is often referred to as half-open scanning,because you don't open a full TCP connection. You send a SYN packet,as if you are going to open a real connection and then wait for aresponse. A SYN/ACK indicates the port is listening (open), while aRST (reset) is indicative of a non-listener. If no response isreceived after several retransmissions, the port is marked asfiltered. The port is also marked filtered if an ICMP unreachableerror (type 3, code 0, 1, 2, 3, 9, 10, or 13) is received. The port is also considered open if a SYN packet (without the ACK flag) is received in response. This can be due to an extremely rare TCP feature known as a simultaneous open or split handshake connection (see https://nmap.org/misc/split-handshake.pdf).

-sT (TCP connect scan)

TCP connect scan is the default TCP scan type when SYN scan isnot an option. This is the case when a user does not have raw packetprivileges. Instead of writing rawpackets as most other scan types do, Nmap asks the underlyingoperating system to establish a connection with the target machine andport by issuing the connect system call. This isthe same high-level system call that web browsers, P2P clients, andmost other network-enabled applications use to establish a connection.It is part of a programming interface known as the Berkeley SocketsAPI. Rather than read raw packet responses off the wire, Nmap usesthis API to obtain status information on each connection attempt.

When SYN scan is available, it is usually a better choice. Nmaphas less control over the high level connect callthan with raw packets, making it less efficient. The system callcompletes connections to open target ports rather than performing thehalf-open reset that SYN scan does. Not only does this take longerand require more packets to obtain the same information, but targetmachines are more likely to log the connection. A decent IDS willcatch either, but most machines have no such alarm system. Manyservices on your average Unix system will add a note to syslog, andsometimes a cryptic error message, when Nmap connects and then closesthe connection without sending data. Truly pathetic services crashwhen this happens, though that is uncommon. An administrator who seesa bunch of connection attempts in her logs from a single system shouldknow that she has been connect scanned.

-sU (UDP scans)

While most popular services on the Internet run over the TCPprotocol, UDP servicesare widely deployed. DNS, SNMP, and DHCP(registered ports 53, 161/162, and 67/68) are three of the mostcommon. Because UDP scanning is generally slower and more difficultthan TCP, some security auditors ignore these ports. This is a mistake, asexploitable UDP services are quite common and attackers certainlydon't ignore the whole protocol. Fortunately, Nmap can help inventoryUDP ports.

UDP scan is activated with the -sU option. Itcan be combined with a TCP scan type such as SYN scan(-sS) to check both protocols during the samerun.

UDP scan works by sending a UDP packet to everytargeted port. For some common ports such as 53 and 161, aprotocol-specific payload is sent to increase response rate, but for most ports the packet isempty unless the --data,--data-string, or --data-lengthoptions are specified.If an ICMP port unreachable error (type 3, code 3) isreturned, the port is closed. Other ICMP unreachable errors (type 3,codes 0, 1, 2, 9, 10, or 13) mark the port as filtered. Occasionally, aservice will respond with a UDP packet, proving that it is open. Ifno response is received after retransmissions, the port is classifiedas open|filtered. This means that the port could be open, or perhapspacket filters are blocking the communication. Version detection(-sV) can be used to help differentiate the trulyopen ports from the filtered ones.

A big challenge with UDP scanning is doing it quickly.Open and filtered ports rarely send any response, leaving Nmap to timeout and then conduct retransmissions just in case the probe orresponse were lost. Closed ports are often an even bigger problem.They usually send back an ICMP port unreachable error. But unlike theRST packets sent by closed TCP ports in response to a SYN or connectscan, many hosts rate limitICMP port unreachable messages by default.Linux and Solaris are particularly strict about this. For example, theLinux 2.4.20 kernel limits destination unreachable messages to one persecond (in net/ipv4/icmp.c).

Nmap detects rate limiting and slows down accordingly to avoidflooding the network with useless packets that the target machine willdrop. Unfortunately, a Linux-style limit of one packet per secondmakes a 65,536-port scan take more than 18 hours. Ideas for speedingyour UDP scans up include scanning more hosts in parallel, doing aquick scan of just the popular ports first, scanning from behind thefirewall, and using --host-timeout to skip slowhosts.

-sY (SCTP INIT scan)

SCTPis a relatively new alternative to the TCP and UDP protocols,combining most characteristics of TCP and UDP, and also addingnew features like multi-homing and multi-streaming. It is mostlybeing used for SS7/SIGTRAN related services but has the potentialto be used for other applications as well.SCTP INIT scan is the SCTP equivalent of a TCP SYN scan.It can be performed quickly, scanning thousands of ports persecond on a fast network not hampered by restrictive firewalls.Like SYN scan, INIT scan is relatively unobtrusive and stealthy,since it never completes SCTP associations. It also allows clear,reliable differentiation between the open,closed, and filteredstates.

This technique is often referred to as half-open scanning,because you don't open a full SCTP association. You send an INITchunk, as if you are going to open a real association and then waitfor a response. An INIT-ACK chunk indicates the port is listening(open), while an ABORT chunk is indicative of a non-listener. If noresponse is received after several retransmissions, the port ismarked as filtered. The port is also marked filtered if an ICMPunreachable error (type 3, code 0, 1, 2, 3, 9, 10, or 13) isreceived.

-sN; -sF; -sX (TCP NULL, FIN, and Xmas scans)

These three scan types (even more are possible with the--scanflags option described in the next section)exploit a subtle loophole in the TCP RFC todifferentiate between open andclosed ports. Page 65 of RFC 793 says that if the[destination] port state is CLOSED .... an incoming segment notcontaining a RST causes a RST to be sent in response. Then the nextpage discusses packets sent to open ports without the SYN, RST, or ACKbits set, stating that: you are unlikely to get here, but if you do, drop thesegment, and return.

When scanning systems compliant with this RFC text, any packetnot containing SYN, RST, or ACK bits will result in a returned RST ifthe port is closed and no response at all if the port is open. Aslong as none of those three bits are included, any combination of theother three (FIN, PSH, and URG) are OK. Nmap exploits this with threescan types:

Null scan (-sN)

Does not set any bits (TCP flag header is 0)

FIN scan (-sF)

Sets just the TCP FIN bit.

Xmas scan (-sX)

Sets the FIN, PSH, and URG flags, lighting the packet up like a Christmas tree.

These three scan types are exactly the same in behavior exceptfor the TCP flags set in probe packets. If a RST packet is received,the port is considered closed, while no responsemeans it is open|filtered. The port is markedfiltered if an ICMP unreachable error (type 3, code0, 1, 2, 3, 9, 10, or 13) is received.

The key advantage to these scan types is that they can sneakthrough certain non-stateful firewalls and packet filteringrouters. Another advantage is that these scan types are a little morestealthy than even a SYN scan. Don't count on this though—mostmodern IDS products can be configured to detect them. The bigdownside is that not all systems follow RFC 793 to the letter. Anumber of systems send RST responses to the probes regardless ofwhether the port is open or not. This causes all of the ports to belabeled closed. Major operating systems that dothis are Microsoft Windows, many Cisco devices, BSDI, and IBM OS/400.This scan does work against most Unix-based systems though. Anotherdownside of these scans is that they can't distinguish open ports fromcertain filtered ones, leaving you with the responseopen|filtered.

-sA (TCP ACK scan)

This scan is different than the others discussed so far in thatit never determines open (or evenopen|filtered) ports. It is used to map outfirewall rulesets, determining whether they are stateful or not andwhich ports are filtered.

The ACK scan probe packet has only the ACK flag set (unless youuse --scanflags). When scanning unfiltered systems,open and closed ports will bothreturn a RST packet. Nmap then labels them asunfiltered, meaning that they are reachable by theACK packet, but whether they are open orclosed is undetermined. Ports that don't respond,or send certain ICMP error messages back (type 3, code 0, 1, 2, 3, 9, 10,or 13), are labeled filtered.

-sW (TCP Window scan)

Window scan is exactly the same as ACK scan except that itexploits an implementation detail of certain systems to differentiateopen ports from closed ones, rather than always printingunfiltered when a RST is returned. It does this byexamining the TCP Window field of the RST packets returned. On somesystems, open ports use a positive window size (even for RST packets)while closed ones have a zero window. So instead of always listing aport as unfiltered when it receives a RST back,Window scan lists the port as open orclosed if the TCP Window value in that reset ispositive or zero, respectively.

This scan relies on an implementation detail of a minority ofsystems out on the Internet, so you can't always trust it. Systemsthat don't support it will usually return all portsclosed. Of course, it is possible that the machinereally has no open ports. If most scanned ports areclosed but a few common port numbers (such as 22,25, 53) are filtered, the system is most likelysusceptible. Occasionally, systems will even show the exact oppositebehavior. If your scan shows 1,000 open ports and three closed or filteredports, then those three may very well be the truly open ones.

-sM (TCP Maimon scan)

The Maimon scan is named after its discoverer,Uriel Maimon.He described the technique inPhrack Magazine issue #49 (November 1996).Nmap, which included this technique, was released two issues later.This technique is exactly the same as NULL, FIN, and Xmas scans, exceptthat the probe is FIN/ACK. According to RFC 793 (TCP), a RST packetshould be generated in response to such a probe whether the port isopen or closed. However, Uriel noticed that many BSD-derived systemssimply drop the packet if the port is open.

--scanflags (Custom TCP scan)

Truly advanced Nmap users need not limit themselves to thecanned scan types offered. The --scanflags option allowsyou to design your own scan by specifying arbitraryTCP flags.Let your creative juices flow, while evadingintrusion detection systemswhose vendors simply paged through the Nmap man page adding specific rules!

The --scanflags argument can be a numericalflag value such as 9 (PSH and FIN), but using symbolic names iseasier. Just mash together any combination of URG,ACK, PSH,RST, SYN, andFIN. For example, --scanflagsURGACKPSHRSTSYNFIN sets everything, though it's not veryuseful for scanning. The order these are specified in isirrelevant.

In addition to specifying the desired flags, you can specify aTCP scan type (such as -sA or -sF).That base type tells Nmap how to interpret responses. Forexample, a SYN scan considers no-response to indicate afiltered port, while a FIN scan treats the same asopen|filtered. Nmap will behave the same way itdoes for the base scan type, except that it will use the TCP flags youspecify instead. If you don't specify a base type, SYN scan isused.

-sZ (SCTP COOKIE ECHO scan)

SCTP COOKIE ECHO scan is a more advanced SCTP scan. It takesadvantage of the fact that SCTP implementations should silentlydrop packets containing COOKIE ECHO chunks on open ports, butsend an ABORT if the port is closed.The advantage of this scan type is that it is not as obvious aport scan than an INIT scan. Also, there may be non-statefulfirewall rulesets blocking INIT chunks, but not COOKIE ECHOchunks. Don't be fooled into thinking that this will make aport scan invisible; a good IDS will be able to detect SCTPCOOKIE ECHO scans too.The downside is that SCTP COOKIE ECHO scans cannot differentiatebetween open and filteredports, leaving you with the state open|filteredin both cases.

-sI <zombie host>[:<probeport>] (idle scan)

This advanced scan method allows for a truly blind TCP port scan of the target (meaning no packets are sent to the target from your real IP address). Instead, a unique side-channel attack exploits predictable IP fragmentation ID sequence generation on the zombie host to glean information about the open ports on the target. IDS systems will display the scan as coming from the zombie machine you specify (which must be up and meet certain criteria). Full details of this fascinating scan type are in the section called “TCP Idle Scan (-sI)”.

Besides being extraordinarily stealthy (due to its blind nature), this scan type permits mapping out IP-based trust relationships between machines. The port listing shows open ports from the perspective of the zombie host. So you can try scanning a target using various zombies that you think might be trusted (via router/packet filter rules).

You can add a colon followed by a port number to the zombie host if you wish to probe a particular port on the zombie for IP ID changes. Otherwise Nmap will use the port it uses by default for TCP pings (80).

-sO (IP protocol scan)

IP protocol scan allows you to determine which IP protocols(TCP, ICMP, IGMP, etc.) are supported by target machines. This isn'ttechnically a port scan, since it cycles through IP protocol numbersrather than TCP or UDP port numbers. Yet it still uses the-p option to select scanned protocol numbers, reportsits results within the normal port table format, and even uses the sameunderlying scan engine as the true port scanning methods. So it isclose enough to a port scan that it belongs here.

Besides being useful in its own right, protocol scandemonstrates the power of open-source software. While the fundamentalidea is pretty simple, I had not thought to add it nor received anyrequests for such functionality. Then in the summer of 2000,Gerhard Riegerconceived the idea, wrote an excellent patch implementing it,and sent it to theannounce mailing list(then called nmap-hackers).I incorporated that patch into the Nmap tree and released a newversion the next day. Few pieces of commercial software have usersenthusiastic enough to design and contribute their ownimprovements!

Protocol scan works in a similar fashion to UDP scan. Insteadof iterating through the port number field of a UDP packet, it sendsIP packet headers and iterates through the eight-bit IP protocol field.The headers are usually empty, containing no data and not even theproper header for the claimed protocol. The exceptions are TCP,UDP, ICMP, SCTP, and IGMP. A proper protocol header for those is included sincesome systems won't send them otherwise and because Nmap already hasfunctions to create them. Instead of watching for ICMP portunreachable messages, protocol scan is on the lookout for ICMPprotocol unreachable messages. If Nmap receivesany response in any protocol from the target host, Nmap marks thatprotocol as open. An ICMP protocol unreachableerror (type 3, code 2) causes the protocol to be marked asclosed while port unreachable (type 3, code 3)marks the protocol open. Other ICMP unreachable errors (type 3, code0, 1, 9, 10, or 13) cause the protocol to be markedfiltered (though they prove that ICMP isopen at the same time). If no response is receivedafter retransmissions, the protocol is markedopen|filtered

-b <FTP relay host> (FTP bounce scan)

An interesting feature of the FTP protocol (RFC 959) issupport for so-called proxy FTP connections. This allows a user toconnect to one FTP server, then ask that files be sent to athird-party server. Such a feature is ripe for abuse on many levels,so most servers have ceased supporting it. One of the abuses thisfeature allows is causing the FTP server to port scan other hosts.Simply ask the FTP server to send a file to each interesting port of atarget host in turn. The error message will describe whether the portis open or not. This is a good way to bypass firewalls becauseorganizational FTP servers are often placed where they havemore access to other internal hosts than any old Internet host would. Nmap supports FTPbounce scan with the -b option. It takes an argumentof the form<username>:<password>@<server>:<port>.<Server> is the name or IP address of avulnerable FTP server. As with a normal URL, you may omit<username>:<password>,in which case anonymous login credentials (user:anonymous password:-wwwuser@)are used. The port number (and preceding colon) may be omitted aswell, in which case the default FTP port (21) on<server> is used.

This vulnerability was widespread in 1997 when Nmap wasreleased, but has largely been fixed. Vulnerable servers are stillaround, so it is worth trying when all else fails. If bypassing afirewall is your goal, scan the target network for port 21 (oreven for any FTP services if you scan all ports with versiondetection) and use theftp-bounceNSE script. Nmap will tell youwhether the host is vulnerable or not. If you are just trying tocover your tracks, you don't need to (and, in fact, shouldn't) limityourself to hosts on the target network. Before you go scanningrandom Internet addresses for vulnerable FTP servers, consider thatsysadmins may not appreciate you abusing their servers in thisway.

Port Scanning Techniques | Nmap Network Scanning (2024)
Top Articles
Latest Posts
Article information

Author: Nicola Considine CPA

Last Updated:

Views: 5754

Rating: 4.9 / 5 (69 voted)

Reviews: 84% of readers found this page helpful

Author information

Name: Nicola Considine CPA

Birthday: 1993-02-26

Address: 3809 Clinton Inlet, East Aleisha, UT 46318-2392

Phone: +2681424145499

Job: Government Technician

Hobby: Calligraphy, Lego building, Worldbuilding, Shooting, Bird watching, Shopping, Cooking

Introduction: My name is Nicola Considine CPA, I am a determined, witty, powerful, brainy, open, smiling, proud person who loves writing and wants to share my knowledge and understanding with you.