Closing ports in Linux is essential for reducing your server’s attack surface and securing the system from unauthorized access. The following procedures, resources, and best practices outline how to securely close ports on a Linux server:
1. Identify Open Ports
- Before closing ports, identify which ports are currently open and determine which ones are unnecessary.
- Use netstat, ss, or lsof to list open ports:
sudo netstat -tuln
or
sudo ss -tuln
2. Close Ports Using Firewall Rules
- iptables: On servers using iptables, you can block incoming traffic on a specific port:
sudo iptables -A INPUT -p tcp --dport PORT_NUMBER -j DROP
Replace PORT_NUMBER with the port you want to close.
- firewalld: On systems using firewalld, you can use this command to remove a port from the public zone:
sudo firewall-cmd --zone=public --remove-port=PORT_NUMBER/tcp --permanent
sudo firewall-cmd --reload
- ufw: For servers using ufw, you can deny access to a specific port:
sudo ufw deny PORT_NUMBER
3. Stop or Disable the Service Using the Port
- If a service you don’t need is listening on an open port, it’s best to stop or disable the service itself rather than just blocking the port.
- Use systemctl to check the status and stop a service:
sudo systemctl status SERVICE_NAME
sudo systemctl stop SERVICE_NAME
sudo systemctl disable SERVICE_NAME
4. Check for Effectiveness
- After applying firewall rules or stopping services, check that the port is closed:
sudo netstat -tuln | grep PORT_NUMBER
or
sudo ss -tuln | grep PORT_NUMBER
Be careful when closing ports related to core services. Accidentally closing SSH can lock you out, so ensure you have alternative access or know how to revert settings in case of an error.