Introduction

Ports and sockets are fundamental concepts that enable network connections to transfer data between computers and applications. Monitoring which ports are open provides valuable visibility into security, functionality and performance of systems like the Raspberry Pi.

The standard netstat command offers powerful yet easy-to-use options for inspecting detailed port and connection status data on Linux distributions. This expert guide will elaborate key technical concepts around ports and demonstrate netstat usage scenarios to manage open ports on a Raspberry Pi device.

Network Ports Explained

A port is logical abstraction that identifies a specific process or networking service. Ports allow multiple networking connections to share a single physical network interface by acting as endpoints that direct traffic.

For example, a server platform may have only one Ethernet port physically, but can host multiple services like HTTP web, FTP file share, SSH remote admin etc. Port numbers differentiate the connections to each service over the one network adapter.

Functionally, ports enable sending requests to the correct destination application. Security-wise, open ports represent potential attack surfaces for exploitation if not secured.

Standardized port numbers allow universal service identification across systems. For example, HTTP web traffic defaults to TCP port 80, DNS resolution uses UDP port 53, and so on.

The Internet Assigned Numbers Authority (IANA) maintains a list of registered port number assignments for common services.

However, many port number usages are not formally registered with IANA. Software applications may use arbitrary ports.

Common Port Types

Well-Known Ports – Numbers 0 to 1023 are reserved for common, standardized services. Used by system (root) processes.

Registered Ports – Numbers 1024 to 49151 identify officially registered services with IANA like HTTP, SSH etc.

Dynamic / Private / Ephemeral Ports – High numbered ports 49152 to 65535 are typically used dynamically by client processes to establish connections.

For example, when a web browser connects to apache web server (port 80), the client connection allocates one of these ephemeral ports. Once closed, that port becomes available again dynamically.

Socket Connections

Internally, ports facilitate connections via socket constructs that link network interfaces with applications. Programming libraries provide socket handling so developers don‘t manage ports directly.

A TCP socket connection is defined by a four-tuple of:

src_address:src_port -> dest_address:dest_port

So a web browser may connect from 192.168.1.100:50132 (dynamic allocated client port) to example.com:80 (registered HTTP service port).

Now that we‘ve explained technical details on networking ports, let‘s see how to inspect them on Linux using netstat.

Introducing the netstat Command

netstat is a standard Linux command line tool used to analyze network configurations, statistics, routes, connections and port status. It‘s included in Raspberry Pi OS and virtually all distros.

In particular, netstat can reveal current open ports and related processes. Understanding open ports is key for security and functionality. Running unneeded services that listen on ports increases exposure to attacks.

So being able to list open ports allows hardening systems by closing down unused listening services and configuring firewall policies to control access. netstat also helps diagnose connectivity issues by showing established connections to services.

First, let‘s demonstrate some useful netstat variations to list open ports.

Listening TCP/UDP Port Examples

List Only Listening TCP Ports

To view TCP protocol ports in listening state ready to receive incoming connections:

pi@raspberrypi:~ $ sudo netstat -ltn
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      
tcp        0      0 127.0.0.1:953          0.0.0.0:*              LISTEN  

This output shows TCP port 22 open for SSH service, and local port 953 open for DNS name resolution service, in listening mode awaiting connections.

List Only Listening UDP Ports

Examining open UDP protocol sockets:

pi@raspberrypi:~ $ sudo netstat -lun
Active Internet connections (only servers)
Proto Recv-Q Send-Q Local Address           Foreign Address         State                 
udp        0      0 0.0.0.0:5353            0.0.0.0:*                                  
udp        0      0 0.0.0.0:1900            0.0.0.0:*   

Indicating UDP ports 5353 and 1900 are listening.

All Open Non-Listening Ports

Whereas above showed only listening ports, to display all other non-listening but open connections:

pi@raspberrypi:~ $ sudo netstat -apn  
Proto Recv-Q Send-Q Local Address          Foreign Address        State        PID/Program name    
tcp        0      0 192.168.1.165:47212    151.101.130.217:443    ESTABLISHED  2245/firefox
tcp        0      0 192.168.1.165:53350    151.101.66.133:443     ESTABLISHED  2245/firefox  

Illustrating active connections from a web browser process with ephemeral source ports allocated.

Now that we can view open listening and non-listening ports, let‘s look at associating ports to running programs.

Identifying Programs on Ports

While seeing simple ports status is helpful, relating open ports to actual running applications is crucial for assessing necessity.

Use netstat‘s -p parameter to tie ports back to owning process IDs and names:

pi@raspberrypi ~ $ sudo netstat -ptln
Active Internet connections (only servers)  
Proto Recv-Q Send-Q Local Address          Foreign Address    State        PID/Program name   
tcp        0      0 0.0.0.0:22             0.0.0.0:*          LISTEN       719/sshd           
tcp        0      0 127.0.0.53:53          0.0.0.0:*          LISTEN       594/systemd-resolve
tcp6       0      0 :::22                  :::*               LISTEN       719/sshd

This directly associates process 719 sshd with open port 22 for example. We can see system standard processes owning most ports.

For further analysis, full path and arguments could be viewed by combining netstat with ps:

pi@raspberrypi ~ $ sudo netstat -ptln | grep sshd
    tcp   0  0 0.0.0.0:22    0.0.0.0:*   LISTEN       719/sshd
pi@raspberrypi ~ $ sudo ps -fp 719
    UID        PID  PPID  C STIME TTY          TIME CMD
    root       719     1  0 Jan14 ?        00:00:00 /usr/sbin/sshd -D

These techniques for process-to-port visibility assist troubleshooting mysterious open ports.

Next let‘s examine identifying unnecessary "noise".

Evaluating Required vs. Unneeded Ports

Once you‘ve established port visibility, intelligently analyzing necessity is crucial before considering closing ports. You want to avoid breaking vital functions that depend on open ports.

Comparing against known required services and carefully tracking changes over time aids analysis:

Service Port Protocol Expected?
SSH 22 TCP Yes
DNS 53 UDP Yes
DHCP 67,68 UDP Yes
HTTP web 80 TCP If running web server
Print Spooler 631 TCP If using printing
Custom App X 1234 TCP Investigate further

Here port 1234 was open but has no expected legitimate usage, prompting deeper scrutiny.

Unexpected open ports could signal compromise if attackers leverage malicious processes. Or someone may have misconfigured firewall policies.

Profiling your regular required baseline open ports versus deviations over time indicates necessary tuning.

Now let‘s move into mitigations around unnecessary ports.

Securing Raspberry Pi Ports

Once careful analysis has identified any unnecessary, risky or excessive open ports, you can tighten security by closing those exposure vectors.

Stopping Associated Services

First, any underlying applications that are causing rogue open ports should be stopped and disabled if not needed:

# Systemctl stop and disable process
sudo systemctl stop myservice
sudo systemctl disable myservice

Stopping the root listening service source closes dependent ports.

Configuring Firewall Rules

Firewall policies provide another mechanism for locking down access to unneeded ports:

Iptables Example Rules

# Block TCP Port 8080
iptables -A INPUT -p tcp --dport 8080 -j DROP  

# Reject UDP Port 1234 Traffic
iptables -A INPUT -p udp --dport 1234 -j REJECT

UFW Example Syntax

# Deny All Inbound UDP 161 Traffic 
ufw deny 161/udp

# Reject TCP 20-25 Port Range
ufw reject 20:25/tcp 

Stateful inspection allows returning traffic for established connections while blocking new unwanted attempts.

Carefully restricting exposed services and ports minimizes chances for exploitation.

Additional Netstat Capabilities

Beyond port visibility, netstat offers many other helpful networking insights.

View Traffic Statistics

Monitor usage metrics like packets sent/received:

pi@raspberrypi ~ $ netstat -s | head 
Ip:
    71046 total packets received
    0 forwarded
    0 incoming packets discarded
    71043 incoming packets delivered 
    68842 requests sent out
Icmp:
    103 ICMP messages received
    0 input ICMP message failed.
    ICMP input histogram:
        destination unreachable: 98
        echo requests: 5 

Detect Port Forwarding

Identify (NAT) forwarding of remote ports into local services:

pi@raspberrypi ~ $ sudo netstat -anp | grep ESTABLISHED
tcp        0      0 192.168.1.8:33386        17.17.17.17:443         ESTABLISHED
tcp        5      0 192.168.1.8:45898        123.123.123.2:22        ESTABLISHED 

Profile Application Connection Behavior

Analyzing ephemeral ports used by applications helps characterize normal behavior for anomaly detection:

App Port Range Avg Connections
Firefox 49200-50000 10
Java App 33000-34000 100
SSH Client 50000-51000 1

Deviations from baseline could indicate issues.

This covers some further advanced netstat functionality beyond inspecting ports alone.

Integrating Netstat with Other Tools

Using netstat output as input to other system tools expands capabilities:

Process Metrics:

# Track Process Connections  
sudo watch "netstat -atnp | grep ESTABLISHED" 

# Count Current Connections per Process
netstat -anop | grep ESTABLISHED | awk ‘{print $5}‘ | cut -d "/" -f 1 | sort | uniq -c | sort -nr

Packet Sniffing:

# Capture Packets with Wireshark
sudo wireshark -k -i any -f "port 22" -Y "tcp.port == 22" 

Network Mapping:

# Further inspect with nmap scan   
nmap -p22 --reason -Pn x.x.x.x 

Integrating the raw data from netstat with programs adds richer functionality.

Now that we‘ve covered utilizing standalone netstat, let‘s explore monitoring ports programmatically.

Automating Port Checks via Scripting

While interactive netstat usage is handy for ad-hoc checks, scripting recurring inspection facilitates continuous monitoring.

For example, here is sample Python script leveraging netstat to email alerts on detected suspicious ports:

#!/usr/bin/env python3
import subprocess
import smtplib
import socket
from email.message import EmailMessage

ALERT_PORTS = [4545, 5983] 

def check_netstat():
    netstat = subprocess.check_output(["netstat", "-ltun"]) 
    lines = str(netstat).split("\\n")
    for line in lines:
        words = line.split()
        if len(words) > 4:  
            localport = words[3].split(":")[-1]
            pid = words[6].split("/")[0]
            if localport in ALERT_PORTS: 
                send_alert(localport, pid)

def send_alert(port, pid):
    msg = EmailMessage()
    hostname = socket.gethostname()    
    msg.set_content(f"Suspicious port {port} opened by PID {pid} on {hostname}")

    msg[‘Subject‘] = f‘[ALERT] Unexpected Port {port} Open‘
    msg[‘From‘] = "portscan@mydomain"
    msg[‘To‘] = "securityteam@mycompany.com"  

    s = smtplib.SMTP("localhost")
    s.send_message(msg)
    s.quit()

if __name__ == "__main__":
    check_netstat()

This demonstrates monitoring for unauthorized open ports and emailing security teams programmatically when finding anomalies.

Expanding netstat capabilties through Python scripting enables automating repetitive checks. The same methodology could also capture trends over time for historical analysis using data stores.

Best Practices for Managing Ports

Based on all we have covered regarding network ports and applying tools like netstat, here are some best practice recommendations:

  • Baseline Open Ports – Document your core required services, ports and data flows. Profile both listening and active connections. Capture typical ephemeral ranges.

  • Monitor Changes – Log and alert on newly opened listen ports. Unexpected connections could indicate compromised processes or misconfigurations.

  • Assess Necessity – Periodically review all listening services still required. Are old test apps still running? Are features being used?

  • Minimize Ports – Have an inventory approval process before opening new ports in firewall policies.

  • Version Update – Upgrade software components frequently to incorporate latest security fixes.

  • Isolate Services – Consider port access rules between network zones to limit lateral exposure.

  • Inspect Internally – Scan open ports from a separate trusted management network to detect unauthorized external exposure.

  • Automate Monitoring – Use scheduled scripts to track port status changes and compliance violations.

Regularly applying these practices maximizes open port visibility, facilitates closing unnecessary services, and locks down your attack surface.

Conclusion

The simple yet powerful netstat tool offers invaluable visibility into open ports, associated services and network connections on Linux systems. Carefully managing open ports by profiling legitimate use cases, hunting down unnecessary listening apps, and configuring strict firewall policies minimizes exposure to attackers.

Regularly monitoring ports status using both interactive and programmed techniques should be a best practice for secured environments, especially powerful Internet of Things devices like the Raspberry Pi.

Combining netstat with other platform tools also unlocks extended analytical capabilities for performance, diagnostics and security alerts automation.

I hope this comprehensive expert guide to checking open ports on Raspberry Pi using netstat delivered helpful details both conceptually and pragmatically! Reach out if you have any other questions.

Similar Posts

Leave a Reply

Your email address will not be published. Required fields are marked *