Protect Systems With TCP/UDP Port-Scanning
IP tools, when used properly, can help system builders tackle set-up and configuration chores, speed troubleshooting and problems resolution, and address all kinds of security issues and concerns. A good IP toolkit is the networking equivalent of a Swiss Army knife. It's chock-full of useful implements, and it's handy to have around for all kinds of uses.
This recipe hinges on a commonly used IP command line utility called netstat, which tracks IP network usage and statistics, but which can also report on UDP and TCP ports. I also used data provided by netstat to create a list of ports used to submit to Steve Gibson's "User Specified Custom Port Probe" (how to access this tool is explained in Step 4 below). My goal was to check how those ports responded to an external scan, and to make sure the network boundary was not open to casual scanning or potential ingress through those addresses.
This recipe is best executed from an Internet gateway machine, especially on networks that use private IP addresses. If you follow this recipe step-by-step, then the Internet gateway machine--the device that bridges the connection to the Internet and local networks--is most likely to display real, meaningful, public IP addresses along with the UDP and TCP port numbers you'll be checking.
Even if the network you're working on uses a router or Internet appliance to bridge the connection between an Internet link and a private network, the techniques I describe here will still work. It just won't be as easy to identify the public side of some connections if you're concerned about some of the port usage you find when you perform the necessary analysis. That said, because many routers and appliances also support the IP command I use in the recipe, you may still be able to apply to the boundary device, even if it's not a Windows machine. But be warned that syntax details and command output may not be exactly the same as what you'll see here.
Understanding TCP and UDP Port Addresses
Whenever an IP-based service or application creates a connection between a client and a server -- or between a pair of peers -- it uses either TCP or UDP as the transport protocol to ferry communications between senders and receivers. For as long as such a connection persists, one or more 16-bit TCP or UDP numeric port addresses (depending on the actual transport protocol used) are used to associate the back-and-forth of network traffic to support communication at the process level. While IP addresses identify unique network interfaces -- which get the traffic to and from sender and receiver -- additional information is needed to deliver data to the process inside which the TCP/IP client, server, or peer activity is underway. This keeps communication flowing.
Because TCP and UDP port numbers are 16 bits in length, they fall in the range of 0 to 65,535, which are the smallest and largest decimal equivalents of the binary numbers that fit inside a 16-bit binary string. This range of values is further subdivided as follows:
- Well-known port addresses fall in the range of 0 to 1,023. These port addresses are permanently associated with specific IP services. Servers that provide these services listen on specific port addresses for connection attempts to let incoming service requests be handled simply and uniformly. This explains why smaller port addresses are used on most machines, in relation to specific well-known IP applications and services.
- Registered port addresses fall in the range from 1,024 to 49,151. These port addresses are sometimes, but not always, associated with other applications or services that fall outside those covered in the well-known port address category, such as proprietary or custom applications, and private services. Addresses in this range can also be dynamically allocated to service temporary client-server or peer-to-peer connections, for as long as ongoing communications between pairs of hosts persist. When registered port addresses are used in dynamic fashion, they're known as ephemeral port addresses, because they come and go as needed.
- Dynamic port addresses -- a.k.a. private port addresses -- fall in the range of 49,152 to 65,535. These port addresses are only used dynamically. They function more or less exclusively as ephemeral ports.
By looking at port numbers in use on a Windows machine, you can tell a fair amount about well-known services or applications in use on those machines. By inspecting port numbers lower than 1,024, you can often determine some of what's going on in the registered port address range by looking for patterns of port use on such computers. That said, Windows does a lot of dynamic port allocation in the range of port addresses from 1,024 through 1,030. This explains why you'll see them in use on many Windows machines, and why so many routine port scans include this range in their coverage. Nevertheless, you can learn a fair amount about patterns of activity on a network by observing which ports are -- or have been -- in use.
There's another terrific benefit to determining which ports are currently in use, and which ones have left traces of their use behind. Namely, the benefit of identifying this set of ports, which you might describe collectively as "those TCP and UDP ports most likely to be used again in the future, if not in use at present," means that you have tagged the most obvious potential means for illicit entry into network and systems in the future, along with the most obvious and likely means for legitimate services and applications to cause traffic to enter or leave that network. Thus, the techniques I describe in this recipe will use information about that set of "ports used" to help you perform a rough and ready perimeter security check. This check can determine whether such ports are open to all comers -- not good, since that can include potential malefactors as well as legitimate servers or users -- or closed to random outside scans. The latter condition is desirable, since those not authorized or invited to use those ports can't easily learn about their existence or use on your networks and systems.
While it's easy to use these tools and techniques to create custom scans of your customer's networks, the recipe I provide here will walk you through two scenarios. They will also help you understand how things work by reporting and analyzing the data that appears from such use. The two scenarios are:
- Windows XP SP2 with Windows Firewall enabled: By default, Windows XP SP2 enables the revamped, built-in Windows Firewall during installation. If another, SP2-aware firewall isn't loaded thereafter -- which will disable Windows Firewall as it itself is enabled -- then the built-in firewall remains enabled and will be used. This scenario is based on a clean re-install of Windows XP and SP2 with no additional firewall software added.
- Windows XP SP2 with Windows Firewall disabled: Although the Windows Firewall is turned on by default after installing SP2 on Windows XP, it's easy to disable. Examining the difference between a scan of the same system without the firewall in place is interesting and, not incidentally, makes a strong argument in favor of some kind of firewall. (Even Microsoft agrees with this need, as its Protect Your PC Web page states. Although the netstat results are identical, the port scan results are not!
As we step through the recipe, I'll provide pointers to additional information on how Windows uses TCP and UDP ports, along with lists of well-known and registered port addresses you can consult for additional information if and when you need it. Because I use built-in Windows utilities and a publicly-accessible Web site to follow this recipe, you don't have to do anything to prepare for that task except to ensure you've got a working Internet connection, access to your favorite browser, and the know-how to start and work at the Windows command line. Let's get started.
System Ingredients
You won't need anything fancy to get started, just:
Windows: Any version of Windows will let you use the netstat utility at the command line, but as of today, only Windows XP SP2 provides the built-in Windows Firewall. So this recipe presumes use of that specific XP version or later. For easy understanding, what you type in will appear in a boldface font. So, for example, "Type this" means type the word "this" at the command line.
A Web Browser: To access the various Web sites with examples and Gibson Research external port scan, you'll need to launch and access URLs using that software. For this recipe, I used Internet Explorer 6 because it's the most popular browser around. But this recipe should work fine with other Web browsers, too.
Scenario 1: Windows XP SP2 with Windows Firewall enabled in five steps
There are five steps involved in capturing the netstat data, extracting the used ports list, and submitting that information to Gibson's Research "User Specified Custom Port Probe" to check the results:
1. Open a Command Prompt window at the Windows XP computer. You can click Start, Run, then type cmd into the Open: textbox in the Run window, then click on OK to open the command window. If your keyboard includes a WinLogo key, click that key and the R key at the same time to open the Run window in a single step; then continue on from there. In future steps, I'll use the notation Win R to denote that key combination.
2. Type netstat -an > portlist.txt at the command line, then hit the Enter key. This executes the netstat command in a way that shows all connections and listening ports using port numbers and numeric IP addresses, rather than using symbolic process, service, or computer names. The results of this scan appear in Code Listing 1, which follows. But the syntax of the command shown is such that the results will be written to a file named portlist.txt that will appear in whatever directory the command is run from. In Code Listing 1, that's C: %5C , which means the file shows up in the root directory for the C: drive on the machine where the command is executed.
Code Listing 1: netstat -an Output
Active Connections
In the first two columns of the table, listings take the general form a.b.c.d: p, where a.b.c.d is a numeric IP address and p is a port address. Note that only TCP ports can show information about connections that ports make, and also show port status. That's because only TCP is a connection-oriented protocol. It gains access to information about what's happening on the other side of the connection. That's also why you see a local address for everything in the table -- the sender information is always known -- but only TCP ports show foreign address and connection state entries in the other two columns.
An address of 0.0.0.0 indicates a general "all senders" or "all receivers" address, depending on the column in which it appears. The loopback address -- 127.0.0.1 -- indicates a connection that may be purely local or may involve a remote connection instead. Also, by comparing the listing from netstat -a to that shown here (netstat -an), you can correlate services or process names with the port numbers and addresses shown here. To help on using netstat, the online help screen is produced in response to the string netstat /?.
As for the TCP ports, here's how to interpret the state entries that appear:
- CLOSE_WAIT: This indicates a connection that's related to a service or process that's not currently active, and is thus closed, but will re-open if and when that service or process is re-activated. (At that point, it will change to ESTABLISHED status).
- ESTABLISHED: This indicates a connection that's open and active at the time the command is executed.
- LISTENING: This indicates a connection to which the computer will respond if an incoming service request shows up on the port number shown. It corresponds to a well-known port address -- here, that's 135 and 445 -- or to something application specific. For example, that's 2869 for BitDefender updates, and 10110 for SpySweeper updates.
- TIME_WAIT: This indicates a connection that gets triggered at a regularly scheduled time, typically to search for updates or perform some other scheduled task.
3. To build your list of port numbers to check, pick all the port numbers shown in the listing, put them in numerical order, and eliminate any duplicates.
For example, Code Listing 1 would produce the list shown below. Note that a range of numbers, such as 1024 to 1030, can be listed as 1024-1030, rather than requiring each individual value to be enumerated.
The easiest way to do this is to edit the file portlist.txt, removing all data except for port numbers. To be safe, you might want to save the results under a different file name, such as portscan.txt. Then open that file in Word or some similar tool, use the text sort utility, and get the numbers in sorted order. Finally, a quick trip through to purge duplicates produces a list of port numbers, grouped into collections of five elements on each line. Individual values are separated by commas, as shown in Code Listing 2 below. Incidentally, this format works well with Gibson's scan, which is limited to 64 unique values per check, wants individual values separated by commas or other punctuation, and can accept ranges as formatted in the following listing. Also, Gibson's scan checks both TCP and UDP ports, so you don't have to worry about specifying which kind to check.
Code Listing 2: Unique port numbers from Code Listing 1, duplicates purged and ranges compressed:
53, 123, 135-139, 445, 500
1025, 1027, 1028, 1034, 1095
1099, 1900, 2748, 2869, 3047
3048, 4493, 4500, 4503-4508, 10110
4. Now it's time to fire up your Web browser, and point it to Gibson Research site. On the home page, click the ShieldsUP! link. Then click the Proceed button on the page that appears next; in turn, this opens the primary ShieldsUP! Web page, where you'll find the Services pane depicted in Figure 1 below (this is also the area on the primary ShieldsUP! page that includes the User Specified Custom Port Probe tool mentioned repeatedly throughout this story). If you keep a text-editor window open with portscan.txt available therein, as well as your Web browser, you can cut lines of text from the editor and paste them into the text-entry box on the screen that appears.
The ShieldsUP! Services pane lets you paste port numbers or ranges, then check them with a click of the right button. The screen shot below shows the first line of text from code listing 2 when pasted as directed:
Next, click the "User Specified Custom Port Probe" button in the Services pane on the primary ShieldsUP! Web page. The results of this activity appear in the next screen shot, which shows that results from scanning the first set of values shows a clean bill of health across the board:
5. Repeat this prescription for the other three lines of text in portscan.txt. First, cut each line of text from the file. Next, paste it into the text box in the ShieldsUP! Services pane. Then click the Custom Port Probe button. Finally, check the results. Hint: Each time you do this, you can click the Back button when you've examined the results and recorded those that don't show a green Stealth value, to return for your next pass.
There are only three possible responses from the ShieldsUp! scan:
- Stealth: This shows up in green. It means the scan evoked no response from the target machine at that port address. This is the most desirable outcome because it indicates the port is invisible to an outside scan.
- Closed: This shows up in pink. It indicates the scan evoked a response that the port exists, but is currently closed to incoming communications. This is not an active danger, but because it can encourage further probing of a system to find open or weak points, it's not a desirable value.
- Open: This shows up in red. It indicates that this port is open, and can in fact be probed further at will. This indicates active exposure. Given known exploits to a specific port address, this means intrusion is possible.
Gibson's advice, with which I concur completely, is that a total stealth rating is the only acceptable result from such a scan. If you try the scan on a Windows XP machine with SP2 installed, that's what you should get from standalone machines by default. On a networked machine, however, it may be necessary to visit the Windows Firewall settings and remove port 445 from the list of ports associated with the File and Printer Sharing service on the gateway machine.
When port 445 is enabled here, I observed that a port in the range from 1025 to 1030 was likely to be open on the Internet interface of the gateway machine for reasons not entirely clear to me -- or, apparently, to Microsoft, since its documentation on the Windows Firewall says this shouldn't happen!
But unclicking the checkbox for port 445 in the Edit a Service window for the Windows Firewall fixes the problem. So if this happens to you, I strongly recommend this strategy. You can reach this window through the following sequence of choices: Start, Control Panel, Security Center, click on Manage Security Settings for Windows Firewall, click the Exceptions tab, highlight File and Printer Sharing in the Programs and Services pane, then click the Edit button below the pane. Make sure the checkbox next to TCP 445 is unchecked in the Edit a Service window. Then OK your way out. Finally, close the Security Center and Control Panel windows.
If anything does show up as either Closed or Open in the Gibson scan results, you'll want to do some research on the port number at Microsoft TechNet. Look for remediation advice. With some digging, this strategy helped me close the only offending item I found on my pristine default XP SP2 installation. So this method should work for you, too.
Scenario 2: Windows XP SP2 with Windows Firewall disabled in just two steps
1. To disable the Windows Firewall, click on Start, Control Panel, Security Center, and Manage Security Settings for Windows Firewall. Then click the Off button on the General tab of the Windows Firewall window. (Warning: This will lead to ongoing notifications and harassment from Windows Security setting until you either turn Windows Firewall back on or replace it with an alternative firewall that Security Center recognizes. So get ready for alert windows to start popping up from the taskbar on a regular basis.) The following screen shot shows turning off the Windows Firewall by clicking the Off radio button (look for the big red X):
2. The port listing from netstat should remain the same, because closing the firewall doesn't affect port usage that netstat reports. But you can repeat steps 1 through 3 in the previous scenario if you like. On the other hand, feel free to jump ahead to the instructions from steps 4 and 5; namely, to cut and paste the contents of the portscan.txt file one line at a time into the textbox in the ShieldsUP! Services pane as you did in the previous example. The following table provides a comprehensive list of results:
Results from Selective Port Scans, Windows Firewall Off:
It should be no surprise that dynamic or actual service ports in the registered port address number range, when used, show up as closed. Windows may need to use them again at some point, and there's no firewall to intercept the scan and block replies. Essentially, the IP stack is doing what it's programmed to do. Protecting itself from scanning was not a design consideration, by any means.
The only real surprise is that Windows holds ports 2869 and 10110 open. But that's due to the way updates for the two applications are built. A firewall reconfigures these connections to respond only to particular incoming IP addresses; otherwise, it does not respond to probes on these port addresses, thereby obscuring these ports from unauthorized scrutiny as well.
If you try this technique, your precise results will vary by the applications and services used on those machines. Your final target results should not vary, however. You're looking for Stealth ratings across the board!
SIDEBAR: Netstat and Port Number References and Resources
For more information about working with the netstat command, please consult the Windows XP Command Line Reference. Or, if you prefer, jump straight to the netstat reference page.
For an explanation of the 0.0.0.0 address in netstat listings, see Microsoft'ss Knowledge Base article175952.
For more information about TCP and UDP ports, get the Microsoft view by starting with Knowledge Base article 174904. The Windows Server 2003 documentation includes the company's most recent description of port assignments for Internet services that it uses.
The official Internet Assigned Numbers Authority (IANA) listing of port numbers was (as of this writing) last updated on October 10; it's a kind of "ultimate reference" on the subject.
Finally, Richard Akerman maintains a broad collection of port-related data, tables, listings, and the best collection of resources pointers I found anywhere. For all this, and more, visit his Any Port in a Datastorm Web page.
Ed Tittel is a writer and trainer based in Austin, TX, who specializes in Windows and security topics, and who can never accumulate enough software toys to play with. He's the author of the forthcoming Wiley book The PC Magazine Guide to Fighting Spyware, Adware, and Malware.
What do you think? Discuss this Recipe in the TechBuilder Recipes Forum today.