11 Oct 2019

Guide to Block and Unblock IP Address in Linux

Want to block IP abusing your Server or the server is facing an abuse attack from a particular IP? Today, we will show you how we can block particular IP address and block IP on a particular Port.

This guide will work on almost all Linux Distribution with iptables. iptables is a user-space utility program that allows a system administrator to configure the tables[2] provided by the Linux kernel firewall (implemented as different Netfilter modules) and the chains and rules it stores. Different kernel modules and programs are currently used for different protocols; iptables applies to IPv4, ip6tables to IPv6, arptables to ARP, and ebtables to Ethernet frames.

iptables requires elevated privileges to operate and must be executed by user root, otherwise, it fails to function. On most Linux systems, iptables is installed as /usr/sbin/iptables and documented in its man pages, which can be opened using man iptables when installed. It may also be found in /sbin/iptables, but since iptables is more like a service rather than an “essential binary”, the preferred location remains /usr/sbin.

Requirements

  • Root Access to the Linux System

Procedure

  1. Login to the server as the root user
  2. Follow the Syntax below for various iptables rules.
    Note – Replace IP-ADDRESS-HEREĀ with the particular IP address and port_numberĀ with the port.

    • Add iptables rule to block IP Address
      iptables -A INPUT -s IP-ADDRESS-HERE -j DROP
    • Add iptables rule to block IP Address access to a specific port
      iptables -A INPUT -s IP-ADDRESS-HERE -p tcp --destination-port port_number -j DROP
    • Drop/Remove iptables rule to unblock IP Address
      iptables -D INPUT -s IP-ADDRESS-HERE -j DROP
    • Drop/Remove iptables rule to unblock IP Address access to a specific port
      iptables -D INPUT -s IP-ADDRESS-HERE -p tcp --destination-port port_number -j DROP
  3. After adding/removing any of the above rules we need to save the iptables rules by the following command.
    iptables-save

With these few commands, we finish the iptables block and unblock rules.

Check/Verify if a particular IP is blocked using iptables.

iptables -L INPUT -v -n | grep "IP-ADDRESS-HERE"

For testing, we will block google.com IP.
find blocked ip

Remove block rule and test ping google.com
remove ip block and test ping