Blocking ip address in linux

How to block an IP using iptables

As a webmaster, you’re eventually going to deal with an abusive user (or several). It’s more or less an inevitable hurdle to doing business online. Maybe they’re spamming your comments section, flooding your server with requests, or harassing your other readers. Either way, you want to get them gone before they cause you any more of a headache than they already have.

Don’t worry. Provided you understand how iptables works – it’s actually fairly easy to do.

We’ll walk you through the process of how to block an IP address, as well as a few of the commands you’re going to want to use.

Let’s get started. Your first step is to log in to your web server either through your control console or through a secure connection. Make sure you’ve got root access – you’re going to need it.

How to block an IP address or IP range

We’ll start with a few of the basic commands.

First off, here’s how to prevent a specific IP Address from accessing your server with the iptables block ip command. Replace [IP] with the IP you actually want to block:

iptables -A INPUT -s [IP] -j DROP

If you’re looking to block a specific range of IP addresses, meanwhile; type in the following, replacing [START] and [END] with the endpoints of the range (via Chron):

iptables -A INPUT -m iprange –src-range [START]-[END] -j DROP

You can also block an entire subnet from accessing your website with

iptables -i eth1 -A INPUT -s [SUBNET ADDRESS] -j DROP

Blocking a connection on a specific interface

Now, let’s say you only want to block a connection through a specific interface. In that case, the command will be as follows:

iptables -A INPUT -i [Interface Name] -s [IP] -j DROP

Читайте также:  Последние версии операционной системы linux

You can add a + to the end of the interface name to block any interface whose name begins with the characters you’ve entered.

How to block a port

If you want to block a connection on a specific port, then you’ll use the following iptables block port command:

iptables -A INPUT -s 65.55.44.100 -p tcp –destination-port 25 -j DROP

Viewing IP Blocks

If at any time you want to view your list of blocked IP addresses, you can either use

iptables -L -v or /sbin/iptables -L INPUT -v

Removing IP Blocks

While viewing that list, you can delete specific entries using the iptables open port command or iptables allow port command. Use the following commands, in order:

iptables -L INPUT -n –line-numbersiptables -D INPUT [LINE]iptables -L INPUT -v -n

Of course, if you know which specific entry you want to be rid of, the following syntax will work just as well using the iptables drop ip command:

iptables -D INPUT -s 1.2.3.4 -j DROP

Assuming you want to log dropped address information, you can also turn on kernel logging with: iptables -i eth1 -A INPUT -s [IP/SUBNET] -j LOG –log-prefix “IP DROP SPOOF A:”

Searching Blocked IPs

Next up, you can search your blocked IP addresses with:

iptables -L INPUT -v -n | grep [IP]

Saving Changes

Finally, in order to save the changes you’ve made to your iptables block list on CENTOS, RHEL, or Fedora, you’ll need to use the command service iptables save.

Additional Commands You Can Use To Block Traffic

The commands above form the basic framework of IP blocking within iptables, but they aren’t exactly comprehensive. If you really want to cut yourself off from an IP address, there are a few additional commands you’ll want to make yourself aware of. They are as follows:

  • -OUTPUT: Prevents TCP connections with a server, and blocks outgoing traffic. Syntax is iptables -A OUTPUT -s [IP] -j DROP
  • -FORWARD: Blocks all forwarding traffic. Syntax is iptables -A FORWARD -s [IP] -j DROP
  • tcp: Like Output, blocks TCP connections. Syntax is iptables -A INPUT -p tcp -s [IP] -j DROP
  • icmp: Blocks port probing. Syntax is -A INPUT -p icmp -s [IP] -j DROP

Building Your iptables Block List

Now that you’ve been primed on the basics of iptables, you can create your own blacklist following these commands:

1. First, flush out all the old default rules and existing rules with the flush command:

Читайте также:  Vmware готовый образ linux

2. Next, change your default chain policy with the following set of commands:

iptables -P INPUT DROPiptables -P FORWARD DROPiptables -P OUTPUT DROP

3. Set up IP blocking as you see fit using the commands in the previous section.

A Few Extra Resources

We’ll leave off today’s piece with a few awesome tips, tricks, and words of advice regarding some of the stuff you can do with iptables. First off, if you’re looking for a script that will automate the banning of abusive IPs, Fail2Ban is an excellent choice.

Next, our knowledge base contains dozens of other tutorials to help you use your Linux server. Our article on securing a linux server is a great start. Continue browsing to learn more.

COMPLETE DIGITAL SERVER SOLUTIONS FOR ALL

Bare Metal Dedicated Servers

A single tenant, physical server allowing you full access to its resources

Professional Hybrid Servers

Virtualized server platform hosted on enterprise-grade physical servers

Scalable Cloud Servers

High-performance and highly-available infrastructure

Managed Colocation

Our next-generation data center facilities

Источник

Как заблокировать IP адреса через ufw

В статье описано, как заблокировать конкретные IP адреса через ufw.

UFW (Uncomplicated Firewall) — стандартная утилита для конфигурирования межсетевого экрана iptables для ОС Ubuntu Linux. Она использует интерфейс командной строки, состоящий из небольшого числа простых команд. UFW — это удобный способ создания базового брандмауэра IPv4 или IPv6, чтобы защитить сервер.

Блокировка определенных IP адресов через ufw

sudo ufw deny from to any 

Для блокировки или закрытия всех пакетов с 192.168.1.5, вводим:

sudo ufw deny from 192.168.1.5 to any 

Показываем статус фаервола включая правила. Для проверки недавно добавленных правил, вводим:

Блокировка определенных IP и номера порта через ufw

ufw deny from to any port

Для блокировки или закрытия «спамерских» IP адресов 202.54.1.5 порта 80, вводим:

sudo ufw deny from 202.54.1.5 to any port 80 

Заново проверяем посредством следующей команды:

Закрытие определенных IP, номеров портов и протоколов через ufw

sudo ufw deny proto from to any port

Для примера блокировка вредоносных IP адресов 202.54.1.1 tcp порта 22, вводим:

$ sudo ufw deny proto tcp from 202.54.1.1 to any port 22 $ sudo ufw status numbered 

Блокировка подсети через ufw. Синтаксис тот же:

$ sudo ufw deny proto tcp from sub/net to any port 22 $ sudo ufw deny proto tcp from 202.54.1.0/24 to any port 22 

Как удалить блокировку и разблокировать IP адресов

$ sudo ufw status numbered $ sudo ufw delete NUM 

Для удаления правила # 4, вводим:

 deny from 202.54.1.5 to any port 80 Proceed with operation (y|n)? y Rule deleted 

Подсказка: UFW, НЕ блокирующий IP-адрес

Чтобы избежать лишних проблем с ненужной блокировкой, необходимо изменить the/etc/ufw/before.rules файл и добавить раздел “Block an IP Address” после “# End required lines”.

$ sudo vi /etc/ufw/before.rules 

Добавьте свое правило для блока от спама или хакеров:

Сохраните и закройте файл. И — перезагрузите брандмауэр:

Источник

How 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.

  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»

find blocked ip

For testing, we will block google.com IP.

remove ip block and test ping

Remove block rule and test ping google.com

Источник

Оцените статью
Adblock
detector