How to Detect and Block Port Scanning
TL;DR
To detect and block port scanning on your Debian 13 server, follow these concise steps:
Install and Configure Fail2Ban: This tool helps to monitor logs and block suspicious IP addresses.
sudo apt update && sudo apt install fail2ban -y # Install Fail2Ban sudo systemctl enable fail2ban # Enable Fail2Ban on boot sudo systemctl start fail2ban # Start Fail2Ban service
Create a custom jail configuration to detect port scans:
sudo nano /etc/fail2ban/jail.local
Add the following configuration:
[portscan] enabled = true port = all filter = portscan logpath = /var/log/syslog maxretry = 1 bantime = 3600
Save and exit, then create the filter:
sudo nano /etc/fail2ban/filter.d/portscan.conf
Add this content:
[Definition] failregex = .*SRC=<HOST>.*DPT=\d+.*
Restart Fail2Ban to apply changes:
sudo systemctl restart fail2ban
Use UFW (Uncomplicated Firewall): Set up UFW to restrict access to only necessary ports.
sudo apt install ufw -y # Install UFW sudo ufw allow ssh # Allow SSH (port 22) sudo ufw enable # Enable UFW
Deny all other incoming connections by default:
sudo ufw default deny incoming # Deny all incoming traffic sudo ufw default allow outgoing # Allow all outgoing traffic
Monitor Logs: Regularly check
/var/log/syslog
for unusual activity.sudo tail -f /var/log/syslog # Monitor syslog for suspicious entries
Caution: Ensure you do not lock yourself out when configuring firewall rules, especially if accessing remotely. Always have a backup access method.
Understanding Port Scanning
Port scanning is a technique used by attackers to identify open ports and services running on a target system. By probing various ports, they can gather information about the system’s vulnerabilities, which can be exploited for unauthorized access or attacks. Understanding how port scanning works is crucial for implementing effective security measures on your Debian 13 server.
There are several types of port scans, including TCP SYN scans, TCP connect scans, and UDP scans. TCP SYN scans are stealthy and often used to bypass detection, as they only send SYN packets to initiate a connection without completing it. In contrast, TCP connect scans attempt to establish a full connection, making them easier to detect.
To monitor for port scanning attempts, you can utilize tools like iptables
and fail2ban
. Setting up iptables
rules can help you block suspicious traffic. For example, you can limit the number of connection attempts from a single IP address:
iptables -A INPUT -p tcp --dport 22 -i eth0 -m conntrack --ctstate NEW -m limit --limit 10/minute --limit-burst 20 -j ACCEPT
iptables -A INPUT -p tcp --dport 22 -i eth0 -j DROP
This configuration allows a maximum of 10 new connections per minute to port 22 (SSH), which helps mitigate brute-force attacks.
Caution is advised when configuring these rules, as overly restrictive settings may inadvertently block legitimate users. Always test your configurations in a safe environment before deploying them on a production server.
Additionally, consider using fail2ban
to automatically block IPs that exhibit suspicious behavior. The following command installs fail2ban
:
# Install fail2ban
apt update && apt install fail2ban -y
By understanding port scanning and implementing these defensive measures, you can significantly enhance the security posture of your Debian 13 server.
Installing and Configuring Fail2Ban
To install and configure Fail2Ban on your Debian 13 server, follow these steps:
First, update your package list and install Fail2Ban:
sudo apt update && sudo apt install fail2ban -y # Install Fail2Ban
Once installed, Fail2Ban’s default configuration file is located at /etc/fail2ban/jail.conf
. However, it’s recommended to create a local configuration file to avoid overwriting changes during updates. Create a copy of the default configuration:
sudo cp /etc/fail2ban/jail.conf /etc/fail2ban/jail.local # Create a local config file
Next, open the local configuration file for editing:
sudo nano /etc/fail2ban/jail.local # Edit the local configuration
In this file, you can enable the default jails and configure settings. To detect and block port scanning, add the following section:
[portscan]
enabled = true
port = all
filter = portscan
logpath = /var/log/syslog
maxretry = 1
bantime = 3600
This configuration enables the portscan jail, sets it to monitor all ports, and bans an IP for one hour after a single detected scan. Adjust bantime
as necessary, but be cautious with very long bans, as they may inadvertently block legitimate users.
Next, create a filter for port scanning. Create a new file:
sudo nano /etc/fail2ban/filter.d/portscan.conf # Create a filter for port scanning
Add the following content to detect port scans:
[Definition]
failregex = .*SRC=(?P<host>\S+).*DPT=(?P<port>\d+)
ignoreregex =
Save and exit the editor. Finally, restart Fail2Ban to apply the changes:
sudo systemctl restart fail2ban # Restart Fail2Ban service
To check the status of Fail2Ban and ensure the portscan jail is active, run:
sudo fail2ban-client status portscan # Check the status of the portscan jail
This setup will help protect your server from potential port scanning attacks effectively.
Using iptables for Blocking Scans
To effectively block port scanning attempts on your Debian 13 server, you can utilize iptables
, a powerful firewall utility. Below are steps to configure iptables
to mitigate the risks associated with port scans.
First, ensure that iptables
is installed and running on your system:
sudo apt update
sudo apt install iptables
Next, you can set up rules to limit the number of connection attempts from a single IP address. This helps in mitigating both port scans and brute-force attacks. The following command allows a maximum of 5 connection attempts within a 60-second window:
sudo iptables -A INPUT -p tcp --dport 1:65535 -m conntrack --ctstate NEW -m recent --set
sudo iptables -A INPUT -p tcp --dport 1:65535 -m conntrack --ctstate NEW -m recent --update --seconds 60 --hitcount 5 -j DROP
In this setup, the first rule tracks new connections, while the second rule drops any IP that exceeds the connection limit.
To further enhance security, you can block all incoming traffic except for specific services you want to allow. For example, if you only want to allow SSH (port 22) and HTTP (port 80), you can use the following commands:
sudo iptables -A INPUT -p tcp --dport 22 -j ACCEPT # Allow SSH
sudo iptables -A INPUT -p tcp --dport 80 -j ACCEPT # Allow HTTP
sudo iptables -A INPUT -m conntrack --ctstate ESTABLISHED -j ACCEPT # Allow established connections
sudo iptables -A INPUT -j DROP # Drop all other incoming traffic
Caution: Be careful when configuring iptables
, as incorrect rules can lock you out of your server. Always ensure you have console access or a backup method to regain access if needed.
Finally, save your iptables
rules to ensure they persist after a reboot:
sudo iptables-save | sudo tee /etc/iptables/rules.v4
By implementing these iptables
rules, you can significantly reduce the risk of port scanning and enhance the overall security of your Debian 13 server.
Monitoring Logs for Suspicious Activity
To effectively monitor logs for suspicious activity related to port scanning, you can utilize built-in tools like iptables
, syslog
, and fail2ban
. These tools help you identify unauthorized access attempts and take appropriate actions.
First, ensure that your system is logging relevant events. Check your rsyslog
configuration to confirm that it captures kernel messages, which include information about network connections. The default configuration usually suffices, but you can verify it by checking the /etc/rsyslog.conf
file.
To monitor logs for unusual connection attempts, you can use the following command to filter out suspicious entries from the auth.log
file:
sudo grep "Failed password" /var/log/auth.log
This command will show you failed login attempts, which may indicate a port scan or brute-force attack.
For more comprehensive monitoring, consider using iptables
to log dropped packets. This can help you identify potential port scanning activity:
sudo iptables -A INPUT -m state --state NEW -p tcp --dport 1:1024 -j LOG --log-prefix "PORT SCAN: " --log-level 4
This rule logs new incoming TCP connections to ports 1 through 1024. Be cautious with logging levels; excessive logging can fill up your disk space quickly. Ensure you have log rotation configured in /etc/logrotate.conf
to manage log sizes.
Additionally, you can use fail2ban
to automatically block IP addresses that exhibit suspicious behavior. Install it with:
sudo apt update && sudo apt install fail2ban
Configure fail2ban
by editing /etc/fail2ban/jail.local
to include rules for SSH and other services. For example:
[sshd]
enabled = true
maxretry = 5
bantime = 3600
This configuration will ban an IP for one hour after five failed login attempts. Always test your configurations to ensure they work as expected without locking out legitimate users.
Using Snort for Advanced Detection
To enhance your port scanning detection capabilities, you can use Snort, a powerful open-source intrusion detection and prevention system. Snort can analyze network traffic in real-time and log packets, making it an excellent tool for identifying suspicious activities, including port scans.
First, install Snort on your Debian 13 server:
sudo apt update
sudo apt install snort
During installation, you will be prompted to configure Snort. Ensure you set the correct network interface (e.g., eth0
or ens33
) for monitoring.
Configuration
Next, configure Snort to detect port scans. Open the Snort configuration file:
sudo nano /etc/snort/snort.conf
Locate the section for rules and ensure the following rule is included to detect port scans:
alert tcp any any -> any any (msg:"Port Scan Detected"; flags:S; threshold:type threshold, track by_src, count 5, seconds 10; sid:1000001; rev:1;)
This rule triggers an alert if there are 5 SYN packets from a single source within 10 seconds, indicating a potential port scan.
Running Snort
To run Snort in intrusion detection mode, use the following command:
sudo snort -A console -c /etc/snort/snort.conf -i eth0
Replace eth0
with your network interface. This command will display alerts in the console.
Caution
Running Snort in a production environment can generate a significant amount of logs, especially if there is high network traffic. It is advisable to configure log rotation and manage the size of log files to prevent disk space issues.
Safe Defaults
For initial testing, consider running Snort in a non-intrusive mode to avoid false positives. You can adjust the threshold values in the rule to suit your environment better. Always review Snort’s logs regularly to fine-tune your detection rules and reduce noise.
Verification
To ensure that your port scanning detection and blocking mechanisms are functioning correctly, you can perform a series of verification steps. This will help confirm that your firewall rules and intrusion detection systems are effectively identifying and mitigating scanning attempts.
First, you can simulate a port scan from another machine on your network using the nmap
tool. If you do not have nmap
installed, you can do so with:
sudo apt update && sudo apt install nmap # Install nmap for testing
Once installed, run a basic scan against your Debian 13 server:
nmap -sS -p 1-65535 <your-server-ip> # Perform a SYN scan on all ports
Monitor your server’s logs to see if the scan is detected. If you have configured fail2ban
or similar tools, you should see entries indicating that the scanning IP has been blocked.
To check the status of fail2ban
, use:
sudo fail2ban-client status # Check fail2ban status
You can also review the logs for any entries related to port scanning:
sudo cat /var/log/fail2ban.log | grep 'Ban' # Look for banned IPs
If you do not see any entries, ensure that your firewall rules are correctly set up. Use the following command to list your current iptables
rules:
sudo iptables -L -n -v # List current iptables rules
Make sure that your rules are configured to drop or reject packets from suspicious IPs.
Caution: Always test in a controlled environment before deploying changes to production systems. Ensure that legitimate traffic is not inadvertently blocked.
For safe defaults, consider allowing only necessary ports and services, and regularly review your logs to adjust your rules as needed.
Buy me a coffee ☕