1. Introduction

iptables is a powerful firewall utility available in Linux systems that allows administrators to control incoming and outgoing network traffic. One common use case is blocking traffic from a specific IP address to protect a server from malicious activity, repeated failed login attempts, or excessive requests.

This document outlines the process to:

  1. Check if an IP is already blocked.
  2. Add a new firewall rule to block it.
  3. Save the configuration to make it persistent after a reboot.

2. Prerequisites

Before performing these steps, ensure the following:

  • Root or Sudo Access: You must have administrative privileges on the server.
  • iptables Installed: Most Linux distributions (CentOS, RHEL, Fedora, Debian, Ubuntu) come with iptables pre-installed.
  • Basic Command Line Knowledge: Familiarity with Linux terminal commands.
  • The IP Address to Block: Ensure you have identified the correct IP to avoid blocking legitimate traffic.

3. Procedure

Step 1: Check if the IP is already blocked

iptables -L -n | grep <IP_address>
  • Explanation:
    • -L lists all current rules.
    • -n avoids DNS lookups and shows raw IP addresses.
    • grep filters the output for the specific IP.
  • If no output appears, the IP is not currently blocked.

Step 2: Block the IP Address

iptables -A INPUT -s <IP_address> -j DROP
  • Explanation:
    • -A INPUT appends the rule to the INPUT chain (incoming traffic).
    • -s <IP_address> specifies the source IP to block.
    • -j DROP tells iptables to silently discard packets from that IP.

Step 3: Save the iptables Rules

iptables-save > /etc/sysconfig/iptables
  • Explanation:
    • iptables-save outputs the current firewall rules.
    • Redirecting to /etc/sysconfig/iptables ensures the rules are applied automatically after a reboot.

4. Notes & Best Practices

  • To remove a blocked IP: iptables -D INPUT -s <IP_address> -j DROP
  • Always double-check the IP before blocking, to avoid disrupting legitimate connections.
  • Consider using fail2ban for automated blocking of repeated offenders.
  • For firewalld-based systems (CentOS 7+), use firewall-cmd instead of direct iptables edits.

5. Conclusion

Blocking specific IP addresses using iptables is an effective way to mitigate certain types of malicious traffic and protect server resources. By following the above steps, administrators can quickly identify, block, and persist these rules, maintaining better control over inbound traffic.

Leave a Reply