Determine which TCP or UDP ports are open on a system

Author: Mark Foster mark@foster.cc FreeBSD

Reviewer: name contact BSD flavour

Reviewer: Yannick Cadin yannick@diablotin.fr FreeBSD/OpenBSD


Concept

Be able to use the utilities found on BSD systems as well as third-party programs to determine which ports are open on a system and which ports are being seen through a firewall.

Introduction

All the BSDs include the netstat and fstat tools. These can be used to list current network status.

The netstat tool provides a wide range of network statistics, but for basic usage use the -a switch to show all sockets and the -n switch to not do DNS and service name lookups. For example:

""# netstat -an ""Active Internet connections (including servers) ""Proto Recv-Q Send-Q Local Address Foreign Address (state) ""tcp4 0 54 192.168.41.27.4372 10.10.242.157.44.5999 ESTABLISHED ""tcp4 0 0 127.0.0.1.6010 *.* LISTEN ""tcp6 0 0 ::1.6010 *.* LISTEN ""tcp4 0 0 *.6666 *.* LISTEN ""tcp4 0 0 127.0.0.1.25 *.* LISTEN ""tcp4 0 0 127.0.0.1.22 *.* LISTEN ""tcp4 0 0 192.168.41.27.22 *.* LISTEN ""tcp6 0 0 *.22 *.* LISTEN ""udp4 0 0 *.1003 *.* ""udp4 0 0 *.111 *.* ""udp4 0 0 192.168.41.27.1004 192.168.41.25.2049

(Note that netstat -a also will list the active UNIX domain sockets, but they aren't shown in the above example.)

The *.* in the "Foreign Address" column indicates that port is listening, even if the state doesn't indicate such as with UDP. To see the service names (as also found in /etc/services) don't use the -n switch.

While fstat is commonly used to identify open files, it also lists internet sockets. It will show the user, command (with PID), port numbers, IP addresses, etc. The following is example fstat output (only showing the "internet" values):

""USER CMD PID FD MOUNT INUM MODE SZ|DV R/W ""reed ssh 14365 4* internet stream tcp ffff800002f27338 192.168.1.2:65310 <-> 10.10.2.6:22 ""root named 2572 21* internet dgram udp ffff800002305840 10.10.10.1:53 ""root ping 442 4* internet raw icmp ffff800002305c00 ""root dhclient 419 5* internet dgram udp ffff800002305d80 *:68 ""root Xorg 338 1* internet stream tcp ffff80000231f630 *:6000 ""root sshd 275 4* internet6 stream tcp ffff80000231fc60 *:22

TODO: finish this

services: service name database

sockstat: list open sockets (not included in base system of OpenBSD, but is in the other BSDs)

nmap: network exploration tool and security scanner

lsof: list open files

Determine which ports are open on a system:

Locally:

""netstat -an ""sockstat -cl

Remotely: nmap hostname or IP

Using sockstat:

""sockstat -cl

Examples

Practice Exercises

More information

netstat(1), services(5) and fstat(1); sockstat(1) and third-party nmap and lsof