Last modified: October 11, 2024

This article is written in: 🇺🇸

Ports

In computer networking, ports serve as endpoints for communication between devices, similar to doors through which data flows in and out of a computer. In today's interconnected digital landscape, network security is paramount. Network ports are critical points that require diligent management and security measures. Unsecured ports can become vulnerabilities, exposing systems to unauthorized access, data breaches, and various cyber threats.

Main idea:

Example:

+-----------------------------------------------+
|                  Server                       |
|        IP Address: 192.168.1.10               |
|                                               |
|  +---------+     +---------+     +----------+ |
|  | Port 22 |     | Port 80 |     | Port 443 | |
|  |  SSH    |     |  HTTP   |     |  HTTPS   | |
|  +----+----+     +----+----+     +----+-----+ |
|       |               |               |       |
+-------+---------------+---------------+-------+
|               |               |
|               |               |
Client Connections over Network

Protocols and Their Associated Ports

There are two primary protocols employed in internet communication, each with its own set of 65,536 ports:

I. TCP (Transmission Control Protocol)

II. UDP (User Datagram Protocol)

Ports in the OSI Model:

+-----------------------+
|       Application     |
+-----------------------+
|      Presentation     |
+-----------------------+
|        Session        |
+-----------------------+
| Transport (TCP/UDP)   |  <-- Ports operate here
+-----------------------+
|         Network       |
+-----------------------+
|       Data Link       |
+-----------------------+
|        Physical       |
+-----------------------+

Common Services and Their Ports

Below is a table detailing some of the most commonly used services and their associated port numbers:

Service Port Number Protocol
HTTP (Web Server) 80 TCP
HTTPS (Secure Web) 443 TCP
FTP (File Transfer) 21 TCP
SSH (Secure Shell) 22 TCP
Telnet 23 TCP
SMTP (Email Send) 25 TCP
DNS (Domain Name) 53 TCP/UDP
DHCP (Dynamic IP) 67, 68 UDP
TFTP (Trivial FTP) 69 UDP
POP3 (Email Receive) 110 TCP
IMAP (Email Access) 143 TCP
SNMP (Network Manage) 161 UDP
LDAP (Directory Access) 389 TCP/UDP
SFTP (Secure File Transfer) 22 TCP
SQL (Database Access) Varied* TCP

Note: SQL services vary in port numbers based on the specific SQL database being used (e.g., MySQL, MSSQL, PostgreSQL, etc.).

The Importance of Securing Network Ports

Securing network ports is a fundamental aspect of network security. Unsecured or misconfigured ports can lead to:

Security Measures for Network Ports

Implementing Firewalls

Firewalls are essential security devices or software that monitor and control incoming and outgoing network traffic based on predetermined security rules. They establish a barrier between trusted internal networks and untrusted external networks.

Managing Open Ports

Monitoring and managing open ports is crucial to prevent unauthorized access.

Using netstat:

sudo netstat -tuln

Expected Output:

Active Internet connections (only servers)
Proto Recv-Q Send-Q Local Address           Foreign Address         State
tcp        0      0 0.0.0.0:22              0.0.0.0:*               LISTEN
tcp6       0      0 :::80                   :::*                    LISTEN
udp        0      0 0.0.0.0:68              0.0.0.0:*

Using ss:

sudo ss -tuln

Expected Output:

Netid State      Recv-Q Send-Q Local Address:Port               Peer Address:Port
udp   UNCONN     0      0      0.0.0.0:68                      0.0.0.0:*
tcp   LISTEN     0      128    0.0.0.0:22                      0.0.0.0:*
tcp   LISTEN     0      128    [::]:80                         [::]:*

Similar to netstat, but ss provides faster and more detailed socket information.

Evaluating Services

Determine if the services running on open ports are required for your system's operation.

Stopping a Service:

sudo systemctl stop service_name

The service service_name has been stopped.

Disabling a Service:

sudo systemctl disable service_name

Expected Output:

Removed /etc/systemd/system/multi-user.target.wants/service_name.service.

The service service_name has been disabled and will not start at boot.

Closing Unused Ports

Closing ports that are not in use reduces the attack surface.

Using Nmap to Scan for Open Ports:

nmap -sT localhost

Expected Output:

Starting Nmap 7.80 ( https://nmap.org ) at 2023-10-08 12:34 UTC
Nmap scan report for localhost (127.0.0.1)
Host is up (0.000012s latency).
Not shown: 997 closed ports
PORT    STATE SERVICE
22/tcp  open  ssh
80/tcp  open  http
631/tcp open  ipp

Nmap done: 1 IP address (1 host up) scanned in 0.03 seconds

Nmap found that ports 22 (SSH), 80 (HTTP), and 631 (Internet Printing Protocol) are open on localhost.

Using ufw to Deny Access:

sudo ufw deny 631/tcp

Expected Output:

Rule added
Rule added (v6)

Incoming TCP traffic on port 631 is now blocked.

Verifying Port Closure:

sudo ss -tuln | grep :631

If there's no output, it indicates that port 631 is no longer listening.

Changing Default Ports

Changing default ports can help obscure services from automated scans and reduce the likelihood of attacks targeting default port numbers.

Example: Changing SSH Port

Editing the SSH Configuration:

sudo nano /etc/ssh/sshd_config

Find the line:

#Port 22

Uncomment and change it to:

Port 2222

Restarting the SSH Service:

sudo systemctl restart sshd

Updating Firewall Rules:

sudo ufw allow 2222/tcp
sudo ufw delete allow 22/tcp

Expected Output:

Rule added
Rule added (v6)
Deleting...
Rule deleted
Rule deleted (v6)

The firewall now allows traffic on port 2222 and blocks port 22.

Verifying SSH on New Port:

sudo ss -tuln | grep :2222

Expected Output:

tcp   LISTEN 0      128    0.0.0.0:2222      0.0.0.0:*
tcp   LISTEN 0      128    [::]:2222         [::]:*

SSH is now listening on port 2222.

When connecting via SSH, specify the new port:

ssh -p 2222 user@hostname

While changing default ports can reduce noise from automated scans, it is not a substitute for proper security measures like strong authentication and encryption.

Securing Port Forwarding

Port forwarding can expose internal services to external networks if not properly configured.

Using iptables to List NAT Rules:

sudo iptables -t nat -L -n -v

Expected Output:

Chain PREROUTING (policy ACCEPT 0 packets, 0 bytes)
pkts bytes target     prot opt in     out     source               destination

Chain INPUT (policy ACCEPT 0 packets, 0 bytes)
pkts bytes target     prot opt in     out     source               destination

Chain OUTPUT (policy ACCEPT 0 packets, 0 bytes)
pkts bytes target     prot opt in     out     source               destination

Chain POSTROUTING (policy ACCEPT 0 packets, 0 bytes)
pkts bytes target     prot opt in     out     source               destination

If there are no entries under the chains, it indicates that no port forwarding rules are set up.

Only forward necessary ports and restrict access using firewall rules.

Example of Adding a Port Forwarding Rule:

Forward external port 8080 to internal port 80 on a specific internal IP:

sudo iptables -t nat -A PREROUTING -p tcp --dport 8080 -j DNAT --to-destination 192.168.1.10:80
sudo iptables -A FORWARD -p tcp -d 192.168.1.10 --dport 80 -m state --state NEW,ESTABLISHED,RELATED -j ACCEPT

Expected Output:

(No output if successful)

Traffic arriving on port 8080 will be forwarded to port 80 on the internal IP 192.168.1.10.

Limit port forwarding to specific external IP addresses.

Enable Logging for Port Forwarding:

sudo iptables -A FORWARD -j LOG --log-prefix "PORT_FORWARDING: "

Expected Output:

(No output if successful)

This rule logs forwarded packets with the prefix "PORT_FORWARDING:" to the system logs.

Monitoring Ports and Processes

Proactive monitoring of network ports and associated processes is essential for detecting anomalies and potential security threats.

Using lsof (List Open Files)

Finding Processes Using a Specific Port:

sudo lsof -i :80

Expected Output:

COMMAND   PID   USER   FD   TYPE DEVICE SIZE/OFF NODE NAME
apache2  1234   root    4u  IPv6  12345      0t0  TCP *:http (LISTEN)
apache2  1235 www-data 4u  IPv6  12345      0t0  TCP *:http (LISTEN)
apache2  1236 www-data 4u  IPv6  12345      0t0  TCP *:http (LISTEN)

sudo lsof -i TCP -sTCP:LISTEN

Expected Output:

COMMAND   PID     USER   FD   TYPE DEVICE SIZE/OFF NODE NAME
sshd     2345     root    3u  IPv4  67890      0t0  TCP *:ssh (LISTEN)
sshd     2345     root    4u  IPv6  67891      0t0  TCP *:ssh (LISTEN)
apache2  1234     root    4u  IPv6  12345      0t0  TCP *:http (LISTEN)

Lists all processes that are in a LISTEN state for TCP connections.

Using netstat

Listing Processes by Port:

sudo netstat -tulpn | grep :22

Expected Output:

tcp   0    0 0.0.0.0:22    0.0.0.0:*    LISTEN   2345/sshd
tcp6  0    0 :::22         :::*         LISTEN   2345/sshd

Using ss (Socket Statistics)

sudo ss -tulwn | grep :80

Expected Output:

tcp   LISTEN 0      128    0.0.0.0:80      0.0.0.0:*
tcp   LISTEN 0      128    [::]:80         [::]:*

Checking Socket Status with ss

ss provides detailed information about network sockets.

ss -s

Expected Output:

Total: 100 (kernel 110)
TCP:   50 (estab 10, closed 30, orphaned 0, synrecv 0, timewait 30/0), ports 0

Transport Total     IP        IPv6
*         110       -         -
RAW       0         0         0
UDP       20        15        5
TCP       20        10        10
INET      40        25        15
FRAG      0         0         0

Provides a summary of socket usage, including the number of TCP connections in different states.

List Established TCP Connections:

ss -tan state established

Expected Output:

State      Recv-Q Send-Q Local Address:Port               Peer Address:Port
ESTAB      0      0      192.168.1.5:22                   192.168.1.10:54321
ESTAB      0      0      192.168.1.5:80                   192.168.1.20:12345

Shows TCP connections that are currently established, including the local and peer addresses and ports.

Count Established Connections:

ss -tan state established | wc -l

Expected Output:

3

The output number indicates the total established TCP connections (including the header line).

Network Scanning with Nmap

Nmap (Network Mapper) is a powerful open-source tool for network exploration and security auditing. It allows you to discover hosts and services on a computer network, thereby creating a "map" of the network.

Main idea:

Common Use Cases:

Basic Nmap Commands

I. Default TCP Scan:

nmap <ip-address>

Expected Output:

Starting Nmap 7.80 ( https://nmap.org ) at 2023-10-08 13:00 UTC
Nmap scan report for example.com (93.184.216.34)
Host is up (0.10s latency).
Not shown: 997 filtered ports
PORT    STATE SERVICE
80/tcp  open  http
443/tcp open  https
8080/tcp open  http-proxy

Nmap done: 1 IP address (1 host up) scanned in 5.23 seconds

Nmap scanned the target IP and found that ports 80, 443, and 8080 are open.

Interpreting Nmap Output

Category Description
Host Status Indicates if the host is up or down.
Port State - open: Accepting connections.
- closed: Not accepting connections but reachable.
- filtered: Status undetermined due to packet filtering.
Service Detection Displays the service name and version running on each open port.

II. TCP SYN Scan (Stealth Scan):

sudo nmap -sS <ip-address>

Expected Output:

Similar to the default scan but may find additional ports due to different scanning technique.

III. Ping Scan (Discover Live Hosts):

nmap -sn 192.168.1.0/24

Expected Output:

Starting Nmap 7.80 ( https://nmap.org ) at 2023-10-08 13:05 UTC
Nmap scan report for 192.168.1.1
Host is up (0.0010s latency).
Nmap scan report for 192.168.1.5
Host is up (0.0015s latency).
Nmap scan report for 192.168.1.10
Host is up (0.0012s latency).
Nmap done: 256 IP addresses (3 hosts up) scanned in 2.50 seconds

Nmap found that hosts at IP addresses 192.168.1.1, 192.168.1.5, and 192.168.1.10 are up.

IV. Enable Version Detection:

nmap -sV <ip-address>

Expected Output:

PORT    STATE SERVICE  VERSION
22/tcp  open  ssh      OpenSSH 7.6p1 Ubuntu 4ubuntu0.3 (Ubuntu Linux; protocol 2.0)
80/tcp  open  http     Apache httpd 2.4.29 ((Ubuntu))
443/tcp open  ssl/http Apache httpd 2.4.29 ((Ubuntu))

Nmap detected the services running on the open ports and identified their versions.

V. Enable OS Detection:

sudo nmap -O <ip-address>

Expected Output:

OS details: Linux 3.10 - 4.11
Network Distance: 1 hop

Nmap estimates the target is running a Linux operating system with a kernel version between 3.10 and 4.11.

VI. Combining Multiple Scans:

sudo nmap -A <ip-address>

Expected Output:

Provides detailed information including open ports, services, versions, OS detection, and traceroute.

VII. Saving Output to a File:

nmap -oN output.txt <ip-address>

Expected Output:

The scan results are saved in output.txt.

Legal Implications:

Challenges

  1. Research reserved ports and explain whether they can be used for purposes other than their designated services. Discuss the potential risks (such as conflicting services) and benefits (like reducing the need for custom port configurations) of using reserved ports for other applications.
  2. Check available port numbers on your system by identifying currently open ports. Use commands like netstat or ss on Linux, or netstat on Windows, and explain the differences in how these tools are used on each platform. Discuss the importance of knowing which ports are open on your system.
  3. Identify which process is running on a specific port using commands like lsof -i :<port> on Linux or netstat -ano on Windows. Explain how this information can help you monitor unknown services and manage resource usage on your system.
  4. After installing a new service or application, determine which port(s) it is using. Use tools like netstat, ss, or lsof on Linux, and explain how you can track and manage the ports used by new services.
  5. Describe the role of ports in networking, focusing on how they facilitate multi-tasking and allow multiple services to operate simultaneously on the same IP address. Discuss how ports enable different applications to communicate independently over the network.
  6. Explain the significance of having 65,535 ports available, and describe how this number is split between TCP and UDP protocols. Discuss how ports are managed and allocated on a system, and why this range of ports is sufficient for most networking needs.
  7. Compare TCP and UDP ports, describing the differences in how they function. Discuss the underlying mechanisms of each protocol and provide examples of when one might be preferred over the other, such as reliability with TCP and speed with UDP.
  8. Use a tool like nmap to view open ports on a server you have access to, and explain how this information can help you understand which services are running. Describe the basic usage of nmap and the insights it provides into a system’s network security.
  9. Research the purpose and ethical considerations of port scanning in cybersecurity. Perform a basic nmap scan on a local IP address or server you control to identify open ports, and explain why ethical hackers use port scanning as part of their methodology.
  10. Investigate the firewall on your system and configure a basic rule to allow or block traffic on a specific port. Test the rule by attempting to access the service associated with the port, and explain why firewalls are essential for protecting open ports from unauthorized access.

Table of Contents

    Ports
    1. Protocols and Their Associated Ports
    2. Common Services and Their Ports
    3. The Importance of Securing Network Ports
    4. Security Measures for Network Ports
      1. Implementing Firewalls
      2. Managing Open Ports
      3. Evaluating Services
      4. Closing Unused Ports
      5. Changing Default Ports
    5. Monitoring Ports and Processes
      1. Using lsof (List Open Files)
      2. Using netstat
      3. Using ss (Socket Statistics)
    6. Checking Socket Status with ss
    7. Network Scanning with Nmap
      1. Basic Nmap Commands
    8. Challenges