CEG 499/699:
Internet Security

College of Engineering & CS
Wright State University
Dayton, Ohio 45435-0001

Port Scanning


Prabhaker Mateti

Abstract:  This lecture introduce the techniques of port scanning that an attacker may use to discover vulnerable services on an Internet host.  We also describe a lab experiment based on three tools: nmap, portsentry, and zonealarm.
This work is supported in part by NSF DUE-9951380.

Table of Contents

  1. Educational Objectives
  2. Port Scanning
    1. Port Numbers
    2. FTP bounce scan
    3. Stealth scan
    4. Fingerprinting an OS
    5. Port scanners
    6. Port scan detection tools
  3. Lab Experiment
  4. Acknowledgements
  5. References

Educational Objectives

  1. Introduce the techniques of port scanning.
  2. Be able to productively use port scanning audit tools such as nmap.
  3. Be able to productively use port scan detector tools

Port Scanning

Port Scanning is one of the most popular reconnaissance techniques attackers use to discover services they can break into. All machines connected to a LAN or connected to Internet via a modem run many services that listen at well-known and not so well-known ports. By port scanning the attacker finds which ports are available (i.e., being listened to by a service).  Essentially, a port scan consists of sending a message to each port, one at a time. The kind of response received indicates whether the port is used and can therefore be probed further for weakness.

The various techniques in scanning are summarized below.  A full understanding of these depends on understanding IP filtering and other firewall techniques.  So re-read this chapter afterwards.

Port Numbers

As you know, public IP addresses are controlled by world-wide registrars, and are unique globally.  Port numbers are not so controlled, but over the decades certain ports have become standard for certain services.  The port numbers are unique only within a computer system.  Port numbers are 16-bit unsigned numbers.  The port numbers are divided into three ranges: the Well Known Ports (0..1023), the Registered Ports (1024..49151), and the Dynamic and/or Private Ports (49152..65535).

Well-Known Ports

All the operating systems now honor the tradition of permitting only the super-user open the ports numbered 0 to 1023.  These well-known ports (also called standard ports) are assigned to services by the IANA (Internet Assigned Numbers Authority, www.iana.org).   On Unix, the text file named /etc/ services (on Windows 2000 the file named %windir%\ system32\ drivers\ etc\ services) lists these service names and the ports they use.  Here are a few lines extracted from this file:

echo             7/tcp     Echo
ftp-data         20/udp    File Transfer [Default Data]
ftp              21/tcp    File Transfer [Control]
ssh              22/tcp    SSH Remote Login Protocol
telnet           23/tcp    Telnet
domain           53/udp    Domain Name Server
www-http         80/tcp    World Wide Web HTTP
Attempts to open a port in the range of 0..1023 by an unprivileged user program will fail. A user program can open any unallocated port higher than 1023.

Non-Standard Ports

By a non-standard port, we simply mean a port whose number is higher than 1023.  In this range also, several services are "standard."  For example,

wins   1512/tcp # Microsoft Windows Internet Name Service
radius 1812/udp # RADIUS authentication protocol
yahoo  5010 # Yahoo! Messenger
x11    6000-6063/tcp   # X Window System


Some malicious program have spread so wide that there are several collections of port numbers known to have been used by these.

Simple Port Scanning Techniques

The simplest port scan tries (i.e., sends a carefully constructed packet with a chosen destination port number) each of the ports 0..65535 on the victim to see which ones are open.

TCP connect():  The connect() system call provided by an OS is used to open a connection to every interesting port on the machine. If the port is listening, connect() will succeed, otherwise the port isn't reachable.

Strobe  A strobe does a narrower scan, only looking for those services the attacker knows how to exploit. The name comes from one of the original TCP scanning programs, though now virtually all scanning tools include this feature.

The ident protocol allows for the disclosure of the username of the owner of any process connected via TCP, even if that process didn't initiate the connection. So, e.g., one can connect to port 80 and then use identd to find out whether the HTTP server is running as root.

Stealth scan

One problem, from the perspective of the attacker, with port scanning is that it is easily logged by the services listening at the ports. They see an incoming connection, but no data, so they log an error. There exist a number of stealth scan techniques to avoid this. A stealth scan is a kind of scan that is designed to go undetected by auditing tools.  Obviously, this is a race -- what are considered stealth scans now may not be so a few months later.

Port scanners scan a host rapidly by firing off packets at different ports.  So, scanning very slowly (taking a day or more) becomes a stealth technique.. Another stealth scanning technique is "inverse mapping", where you try to find out all hosts on a network by generating "host unreachable" ICMP-messages for those IPs that do not exist. Since these messages may be generated by any TCP/IP packet one may send meaningless packets (e.g. RST packets sent without any previous packet).

Fragmented packets The scanner splits the TCP header into several IP fragments. This bypasses some packet filter firewalls because they cannot see a complete TCP header that can match their filter rules.  Some packet filters and firewalls do queue all IP fragments (e.g.,  the CONFIG _IP _ALWAYS _DEFRAG option in Linux enables it in the kernel), but many networks cannot afford the performance loss caused by the queuing.

SYN scanning: This technique is also called half-open scanning, because a TCP connection is not completed. A SYN packet is sent (as if we are going to open a connection), and the target host responds with a SYN+ACK, this indicates the port is listening, and an RST indicates a non- listener.  The server process is never informed by the TCP layer because the connection did not complete.

FIN scanning: The typical TCP scan attempts to open connections (at least part way). Another technique sends erroneous packets at a port, expecting that open listening ports will send back different error messages than closed ports.  The scanner sends a FIN packet, which should close a connection that is open.  Closed ports reply to a FIN packet with a RST. Open ports, on the other hand, ignore the packet in question. This is required TCP behavior.  If no service is listening at the target port, the operating system will generate an error message. If a service is listening, the operating system will silently drop the incoming packet. Therefore, silence indicates the presence of a service at the port. However, since packets can be dropped accidentally on the wire or blocked by firewalls, this isn't a very effective scan.

Other techniques that have been used consist of XMAS scans where all flags in the TCP packet are set, or NULL scans where none of the bits are set. However, different operating systems respond differently to these scans, and it becomes important to identify the OS and even its version and patch level.

SOCKS port probe

SOCKS is a system that allows multiple machines to share a common Internet connection.  The reason that attackers scan for this is because a large percentage of users misconfigure SOCKS.

Many products support SOCKS. A typical product for home users is WinGate, which is installed on a single machine that actually connects to the Internet. All the other machines within the home connect to the Internet through the machine running WinGate.

A misconfigured SOCKS permits arbitrary the sources and destinations. Just as it allows internal machines access to the Internet, it will allow external machines to access the internal home network.  Most importantly, it may allow a attacker access to other Internet machines through your system. This allows the attacker to hide his/her true location.

IRC chat servers will often scan clients for open SOCKS servers. They will kick off such people with a message indicating how to fix the problem. If you receive such a message, then you can check  the client to see if it is a WinGate bot performing such a check. A false-positive may occur if an application is temporarily unavailable. In this case, it will look like your internal machines are "attacking" the SOCKS server.

Bounce Scans

The ability to hide their tracks is important to attackers. Therefore, attackers scour the Internet looking for systems they can bounce their attacks through.

FTP bounce scanning takes advantage of a vulnerability of the  FTP protocol itself.  It requires support for proxy ftp connections.  This bouncing through an FTP server hides where the attacker comes from. This technique is similar to IP spoofing in that it hides where the attacker comes from. For example, evil.com establishes a control connection to the FTP server-PI (protocol interpreter) of target.com . Then  request that the server-PI initiate an active server-DTP (data transfer process) to send a file anywhere on the Internet. 

A port scanner can exploit this to scan TCP ports from a proxy ftp server. Thus you could connect to an FTP server behind a firewall, and then scan ports that are more likely to be blocked (e.g., port 139). If the ftp server allows reading from and writing to a directory (such as /incoming), you can send arbitrary data to ports that you do find open. Our technique is to use the PORT command (of FTP) to declare that our passive user-DTP is listening on the target box at a certain port number. Then we try to LIST the current directory, and the result is sent over the server-DTP channel. If our target host is listening on the specified port, the transfer will be successful (generating a 150 and a 226 response). Otherwise we will get "425 Can't build data connection: Connection refused." Then we issue another PORT command to try the next port on the target host. The advantages to this approach are obvious (harder to trace, potential to bypass firewalls). The main disadvantages are that it is slow, and that some FTP server implementations have finally  disabled the proxy "feature".

Finger: Most finger servers allow commands to be forwarded through them. Finger supports recursive queries. A query such as "rob@foo@bar" will ask "bar" to resolve "rob@foo", causing "bar" to query "foo". This technique can be used to hide the original source of the request.

E-mail: Spammers try to relay their spam through SMTP servers. As a result, probes for SMTP are commonly seen by machines on the Internet.

SOCKS Allows almost any protocol to be tunneled through the intermediate machine. As a result, attackers probing for SOCKS is common scan seen on the Internet.

HTTP proxy: Most web servers support proxying so that all web traffic can be directed to a single server for filtering as well as caching to improve performance. A lot of these servers are misconfigured to allow proxying of any request from the Internet, allowing attackers to relay attacks against web-sites through a third party.  Probes for HTTP proxies is one of the more common scans seen today.

IRC BNC:  Attackers love to hide their IRC identities by bouncing their connections through other machines. A particular program called "BNC" is used for this purpose on compromised machines.

UDP Scanning

Port scanning usually means scanning for TCP ports, which are connection-oriented and therefore give good feedback to the attacker. UDP responds in a different manner. In order to find UDP ports, the attacker generally sends empty UDP datagrams. If the port is listening, the service should send back an error message or ignore the incoming datagram. If the port is closed, then most operating systems send back an "ICMP Port Unreachable" message. Thus, you can find out if a port is NOT open, and by exclusion determine which ports are open. Neither UDP packets, nor the ICMP errors are guaranteed to arrive, so UDP scanners of this sort must also implement retransmission of packets that appear to be lost (or you will get a bunch of false positives). Also, this scanning technique is slow because of compensation for machines that implement the suggestions of RFC 1812 and limit ICMP error message rate. For example, the Linux kernel  limits destination unreachable message generation to 80 per 4 seconds, with a 1/4 second penalty if that is exceeded.

Some people think UDP scanning is lame and pointless -- not so.  Consider the recent Solaris rpcbind hole (Sun Microsystems  Security Bulletin Bulletin Number: #00167, April 8, 1998).  Rpcbind can be found hiding on an undocumented UDP port somewhere above 32770. So it doesn't matter that port 111 is blocked by the firewall. But can you find which of the more than 30,000 high ports it is listening on? With a UDP scanner you can!

UDP recvfrom() and write() scanning: While non-root users cannot read port unreachable errors directly, Linux informs the user indirectly when they have been received. For example, a second write() call to a closed port will usually fail. A lot of scanners, e.g.,  netcat and pscan.c (written by pluvius@dhp.com, Jan 22, 1995), do this. Note also that recvfrom() on non-blocking UDP sockets usually return the error EAGAIN ("Try Again") if the ICMP error hasn't been received, and ECONNREFUSED ("Connection refused") if it has.

ICMP Scanning

This isn't really port scanning, since ICMP does not have a port abstraction. But it is sometimes useful to determine what hosts in a network are up by pinging them all.  ICMP scanning can be done in parallel, so it can be quite fast. 

Fingerprinting an OS

Fingerprinting is the technique of interpreting the responses of a system in order to figure out what it is. Unusual combinations of data are sent to the system in order to trigger these responses. Systems respond the same with correct data, but they rarely respond the same way  for wrong data.

Port Scanning Tools

There are three security audit tools that stand out: SAINT, nmap, and nessus.  Of these, nmap is clearly and primarily a port scanner; so it is discussed here.  SAINT and nessus are discussed in the chapter on Security Audit.

The nmap is a widely known port scanner written by Foydor.  According to its author, "nmap is a utility for port scanning large networks, although it works fine for single hosts. The guiding philosophy for the creation of nmap was TMTOWTDI (There's More Than One Way To Do It). This is the Perl slogan, but it is equally applicable to scanners. Sometimes you need speed, other times you may need stealth. In some cases, bypassing firewalls may be required. Not to mention the fact that you may want to scan different protocols (UDP, TCP, ICMP, etc.). You just can't do all this with one scanning mode. And you don't want to have 10 different scanners around, all with different interfaces and capabilities. Thus I incorporated virtually every scanning technique I know into nmap."  www.nmap.org.

Part of the lab experiment is based on nmap.

Port scan detection tools

Writing a non-stealth scan detector is straightforward in Unix, in which you open a SOCK_RAW, make the protocol type IPPROTO_IP, then call recvfrom() and capture the packets and analyze them.  Discovering stealth scans requires kernel level work.  One signature that could be used for detecting port scans is "several packets to different destination ports from the same source address within a short period of time". Another such signature could be "SYN to a non-listening port". Obviously, there are many other ways to detect port scans. 

Remember that an attacker might also be IP source address spoofing.  So a detector can inform us that we have been port-scanned but not necessarily where from.  However, port scanners sometimes leak extra information that can be used to tell something about the real origin of a spoofed port scan. For example, if the packets we receive have an IP TTL of 255 at our end, we know for sure that they're being sent from our local network regardless of what the source address field says. However, if TTL is 250, we can only tell that the attacker was no more than 5 hops away, we cannot tell how far exactly she was for sure. Starting TTL and source port numbers can also give us a hint of what port scanner type (for "stealth" scans) or  operating system (for full TCP connection scans) is used by the attacker. We can never be sure though. For example, nmap sets TTL to 255 and source port to 49724, while Linux kernel sets TTL to 64.

Lab Experiment

In the context of this lab experiment, it is worth reproducing a few paragraphs from the SAINT manuals:

Being a very unfriendly neighbor It is generally considered to be very rude and anti-social behavior to scan someone else's hosts or networks without the explicit permission of the owner. Always ask if it'd be okay to scan outside of your own networks.

Please be considerate and smart; unauthorized scanning of your Internet neighbors, even if you think you're doing them a favor, can be seen as a serious transgression on your part, and could engender not only ill will or bad feelings, but legal problems as well.

Attacking vs. probing vs. scanning What is an attack, or a probe, or a scan? It's not always clear, especially as system administrators are getting more savy and aware of the enormous amount of traffic present on the Internet. For instance, is a finger from a remote site an attack? Without knowing any of the motivations involved, it can't be ascertained. "Finger wars", or two sites that use the "tcp wrappers" or similar software that will automatically finger a remote site that connects to it can bring down hosts inadvertently.

Be aware that many of the probes will generate messages on the console or set off various alarms on the remote target, however, so you should be aware of the potential for false alarms and accusations that might be leveled against you.

Objective:  Deliberately misconfigure certain services on a machine. Run a port scanner productively on another machine and discover the vulnerabilities of the first.

All work should be carried out in Operating Systems and Internet Security (OSIS) Lab, 429 Russ.   Use any of the PCs numbered 19 to 30.  No other WSU facilities are allowed. 

  1. This lab requires you to read the man pages that come bundled with the tarballs and also to design the missing details in the experimental setup. You will try out in the lab experiment
    1. PortSentry  www.psionic.com/abacus/ portsentry/  
    2. ZoneAlarm (download free for personal use from http://www.zonelabs.com/) that can detect port scans.
    3. nmap.
  2. Both a GUI front end called nmapfe, and nmap are installed on all machines in the lab. Local copies of portsentry, and zonealarm are located in the anonymous FTP area on the machine Cocke. osis. cs. wright. edu.  Download these  into your Zip disk. Among these files ZoneAlarm is a self-install executable for Windows NT/2000; the others are for Linux.
  3. Choose three machines: P0, P1 and P2.  Connect all three into an Ethernet switch.  You will login as root (administrator) on all three machines.
  4. On P0, build and install portsentry.  Save the executables onto your zip disk.  You will be using these on P1.
  5. On P1 a deliberately weaken a few services of your choice.  Add a few more services to this setup.  Start portsentry on P1.
  6. Boot the machine P2 into Windows NT.  If zonealarm is not installed, install it.  Run it.
  7. Start nmapfe on P0 to probe all ports on P1 and P2. 
  8. Restore P1 to its original configuration.
  9. Turn in the details of this experiment, and the logs generated on all the machines.  Turn in also your analysis regarding the discoveries made by nmap.


This article has been pieced together from the materials on the site http://advice.networkice.com/, and from the documentation of nmap.


  1. Ron Gula, How to Handle and Identify Network Probes, April 1999, www.securitywizards.com [Local Copy] Required Reading.

  2. Hobbit, The FTP Bounce Attack, The original paper on the subject.  http://www.insecure.org/nmap/ hobbit.ftpbounce.txt Reference.
  3. Fyodor, Remote OS detection via TCP/IP Stack Finger Printing. Written: October 18, 1998 Last Modified: April 10, 1999. http://www.insecure.org/nmap/nmap-fingerprinting-article.html   Required Reading.
  4. solar designer, Designing and Attacking Port Scan Detection Tools, Phrack Magazine, Volume 8, Issue 53 July 8, 1998, article 13 of 15,  www.phrack.com or  http://phrack.infonexus.com/ search.phtml?view&article=p53-13  Recommended Reading.
  5. List of ports used by Trojans, http://www.simovits.com/nyheter9902.html Reference.
06/29/01 01:28:54 PM
Open Content Copyright 2001 pmateti@cs.wright.edu