Защита сайтов на wordpress с помощью fail2ban

Adjusting the General Settings within Fail2Ban

To get started, we need to adjust the configuration file that uses to determine what application logs to monitor and what actions to take when offending entries are found. The supplied file is the main provided resource for this.

To make modifications, we need to copy this file to . This will prevent our changes from being overwritten if a package update provides a new default file:

Open the newly copied file so that we can set up our Nginx log monitoring:

Changing Defaults

We should start by evaluating the defaults set within the file to see if they suit our needs. These will be found under the section within the file. These items set the general policy and can each be overridden in specific jails.

One of the first items to look at is the list of clients that are not subject to the policies. This is set by the directive. It is sometimes a good idea to add your own IP address or network to the list of exceptions to avoid locking yourself out. This is less of an issue with web server logins though if you are able to maintain shell access, since you can always manually reverse the ban. You can add additional IP addresses or networks delimited by a space, to the existing list:

/etc/fail2ban/jail.local

Another item that you may want to adjust is the , which controls how many seconds an offending member is banned for. It is ideal to set this to a long enough time to be disruptive to a malicious actor’s efforts, while short enough to allow legitimate users to rectify mistakes. By default, this is set to 600 seconds (10 minutes). Increase or decrease this value as you see fit:

/etc/fail2ban/jail.local

The next two items determine the scope of log lines used to determine an offending client. The specifies an amount of time in seconds and the directive indicates the number of attempts to be tolerated within that time. If a client makes more than attempts within the amount of time set by , they will be banned:

/etc/fail2ban/jail.local

Setting Up Mail Notifications (Optional)

Once you have your MTA set up, you will have to adjust some additional settings within the section of the file. Start by setting the directive. If you set up Postfix, like the above tutorial demonstrates, change this value to “mail”:

/etc/fail2ban/jail.local

/etc/fail2ban/jail.local

/etc/fail2ban/jail.local

Explore Available Settings

The version of we defined above is a good start, but you may want to adjust a number of other settings. Open , and we’ll examine some of the defaults. If you decide to change any of these values, remember that they should be copied to the appropriate section of and adjusted there, rather than modified in-place.

Default Settings for All Jails

First, scroll through the section.

You can adjust the source addresses that Fail2ban ignores by adding a value to the parameter. Currently, it is configured not to ban any traffic coming from the local machine. You can include additional addresses to ignore by appending them to the end of the parameter, separated by a space.

The parameter sets the length of time that a client will be banned when they have failed to authenticate correctly. This is measured in seconds. By default, this is set to 600 seconds, or 10 minutes.

The next two parameters that you want to pay attention to are and . These work together to establish the conditions under which a client should be banned.

The variable sets the number of tries a client has to authenticate within a window of time defined by , before being banned. With the default settings, Fail2ban will ban a client that unsuccessfully attempts to log in 3 times within a 10 minute window.

This parameter configures the action that Fail2ban takes when it wants to institute a ban. The value is defined in the file shortly before this parameter. The default action is to simply configure the firewall to reject traffic from the offending host until the ban time elapses.

Settings for Individual Jails

After , we’ll encounter sections configuring individual jails for different services. These will typically include a to be banned and a to monitor for malicious access attempts. For example, the SSH jail we already enabled in has the following settings:

/etc/fail2ban/jail.local

In this case, is a pre-defined variable for the standard SSH port, and uses a value defined elsewhere in Fail2ban’s standard configuration (this helps keep portable between different operating systems).

Another setting you may encounter is the that will be used to decide whether a line in a log indicates a failed authentication.

The value is actually a reference to a file located in the directory, with its extension removed. This file contains the regular expressions that determine whether a line in the log is bad. We won’t be covering this file in-depth in this guide, because it is fairly complex and the predefined settings match appropriate lines well.

However, you can see what kind of filters are available by looking into that directory:

If you see a file that looks to be related to a service you are using, you should open it with a text editor. Most of the files are fairly well commented and you should be able to tell what type of condition the script was designed to guard against. Most of these filters have appropriate (disabled) sections in that we can enable in if desired.

For instance, pretend that we are serving a website using Nginx and realize that a password-protected portion of our site is getting slammed with login attempts. We can tell Fail2ban to use the file to check for this condition within the file.

This is actually already set up in a section called in our file. We would just need to add an parameter for the jail to :

/etc/fail2ban/jail.local

And restart the service:

Сервер

Fail2ban состоит из двух частей: клиента и сервера. Сервер многопоточен и прослушивает в сокете Unix-команды. Сам сервер ничего не знает о файлах конфигурации. Таким образом, при запуске сервер находится в состоянии «по умолчанию», в котором не определены никакие джейлы. Для fail2ban-сервера доступны следующие опции:

Fail2ban-server не должен использоваться напрямую, за исключением случаев отладки

Опция -s , вероятно, является самой важной и используется для установки пути сокета. Таким образом, можно запускать несколько экземпляров Fail2ban на разных сокетах

Однако это необязательно, поскольку Fail2ban может одновременно запускать несколько джейлов.

Fail2ban-client является интерфейсом Fail2ban. Он подключается к файлу сокета сервера и отправляет команды для настройки и управления сервером. Клиент может прочитать конфигурационные файлы или просто быть использован для отправки одной команды на сервер с помощью командной строки или интерактивного режима (который активируется опцией -i). Fail2ban-client также может запустить сервер. Для fail2ban-клиента доступны следующие параметры:

Все настройки в файлах конфигурации можно настроить вручную. Конфигурация – это простой и эффективный способ настройки сервера. Fail2ban-client переводит конфигурацию в набор команд. Тем не менее, fail2ban-client имеет еще две команды для внутреннего использования. Первая – это старт. При вводе команды $ fail2ban-client start  – клиент сначала попытается развернуть экземпляр сервера. Затем клиент ожидает запуска сервера, отправив ему запросы ping. Как только сервер отвечает на эти запросы, fail2ban-клиент анализирует конфигурацию и отправляет соответствующие команды на сервер.

Вторая команда – перезагрузка. Осуществляется вводом команды: $ fail2ban-client reload

Работа со списком заблокированных адресов

Просмотр

Получить статистику заблокированных адресов можно следующей командой:

fail2ban-client status <имя правила>

Получить список правил можно командой:

fail2ban-client status

При наличие заблокированных IP-адресов мы увидим, примерно, следующее:

`- action
   |- Currently banned: 2
   |  `- IP list:       31.207.47.55 10.212.245.29

С помощью iptables:

iptables -L -n —line

С помощью firewall-cmd:

firewall-cmd —direct —get-all-rules

Удаление

Средствами fail2ban:

Для удаление адреса из списка вводим:

fail2ban-client set <имя правила> unbanip <IP-адрес>

например:

fail2ban-client set ssh unbanip 31.207.47.55

С помощью iptables:

iptables -D <цепочка правил> -s IP-адрес

например:

iptables -D fail2ban-ssh -s 10.212.245.29

С помощью firewall-cmd:

firewall-cmd —direct —permanent —remove-rule <правило>

например:

firewall-cmd —direct —permanent —remove-rule ipv4 filter f2b-sshd 0 -s 188.134.7.221

После необходимо перечитать правила:

firewall-cmd —reload

Introduction

The problem

Brute-force break-in attempts are quite frequent against an SSH server and other password protected internet-services (such as ftp,pop,…). Automated scripts try multiple combinations of username/password (brute-force, dictionary attack) and sometimes changing the port to something other than the default can’t be done. Furthermore, scouring your log files yourself is not only time consuming, but can be difficult too.

Fail2ban attempts to alleviate these issues by providing an automated way of not only identifying possible break-in attempts, but acting upon them quickly and easily in a user-definable manner.

The solution

Here is a list of the most important features available in Fail2ban:

  • client/server
  • multithreaded
  • autodetection of the date/time format
  • wildcard support in logpath option
  • support for a lot of services (sshd, apache, qmail, proftpd, sasl, asterisk, etc)
  • support for several actions (iptables, tcp-wrapper, shorewall, mail notifications, etc)

The code has been completely rewritten since 0.6.x. Fail2ban is entirely written in Python and thus should work on most of the *nix systems.

Configure Local Settings

The Fail2ban service keeps its configuration files in the directory. There, you can find a file with default values called . Since this file may be overwritten by package upgrades, we shouldn’t edit it in-place. Instead, we’ll write a new file called . Any values defined in will override those in .

contains a section, followed by sections for individual services. may override any of these values. Additionally, files in can be used to override settings in both of these files. Files are applied in the following order:

  1. , alphabetically
  2. , alphabetically

Any file may contain a section, executed first, and may also contain sections for individual jails. The last vavalue set for a given parameter takes precedence.

Let’s begin by writing a very simple version of . Open a new file using (or your editor of choice):

Paste the following:

/etc/fail2ban/jail.local

This overrides three settings: It sets a new default for all services, makes sure we’re using for firewall configuration, and enables the jail.

Exit and save the new file (in , press Ctrl-X to exit, y to save, and Enter to confirm the filename). Now we can restart the service using :

The command should finish without any output. In order to check that the service is running, we can use :

You can also get more detailed information about a specific jail:

WordPress и fail2ban

Для того чтобы неудачные попытки входа в админку wordpress пресекались скриптами fail2ban необходимо установить один единственный плагин WP fail2ban. Плагин не имеет настроек и делает всего-лишь одну единственную вещь — он выводит в лог auth.log каждую попытку авторизации на сайте. Таким образом настроив фильтр и джейл можно блокировать хосты пытающиеся проникнуть на ваш сайт.

К слову фильтры идут в комплекте с плагином и вам необходимо их просто скопировать в папку filter.d из папки плагина на сервере. Выглядят они следующим образом:

# Fail2Ban filter for WordPress hard failures
#



before = common.conf



_daemon = (?:wordpress|wp)

failregex = ^%(__prefix_line)sAuthentication attempt for unknown user .* from <HOST>$
 ^%(__prefix_line)sBlocked user enumeration attempt from <HOST>$
 ^%(__prefix_line)sBlocked authentication attempt for .* from <HOST>$
 ^%(__prefix_line)sPingback error .* generated from <HOST>$
 ^%(__prefix_line)sSpam comment \d+ from <HOST>$
 ^%(__prefix_line)sXML-RPC authentication attempt for unknown user .* from <HOST>$
 ^%(__prefix_line)sXML-RPC multicall authentication failure from <HOST>$

ignoreregex =

# DEV Notes:
# Requires the 'WP fail2ban' plugin:
# https://wordpress.org/plugins/wp-fail2ban/
#
# Author: Charles Lecklider

Теперь создаем файл wordpress.conf в папке /etc/fail2ban/jail.d следующего содержания:

enabled = true
filter = wordpress-hard
logpath = /var/log/auth.log
maxretry = 3
port = http,https
bantime = 3600

После этого перезагружаем демона fail2ban и наблюдаем за логами или почтовым ящиком, если вы настроили оповещение о блокировках.

tail -f /var/log/fail2ban.log
2017-03-01 08:52:52,825 fail2ban.filter : INFO  Found 78.110.10.2
2017-03-01 08:53:32,786 fail2ban.filter : INFO  Found 52.14.24.93
2017-03-01 08:53:35,519 fail2ban.filter : INFO  Found 52.14.24.93
2017-03-01 08:56:19,436 fail2ban.filter : INFO  Found 14.141.71.26
2017-03-01 08:59:11,741 fail2ban.filter : INFO  Found 185.104.192.93
2017-03-01 09:00:13,419 fail2ban.filter : INFO  Found 52.14.24.93
2017-03-01 09:00:13,422 fail2ban.filter : INFO  Found 52.14.24.93
2017-03-01 09:00:15,872 fail2ban.filter : INFO  Found 52.14.24.93
2017-03-01 09:00:16,319 fail2ban.actions : NOTICE  Ban 52.14.24.93
2017-03-01 09:00:16,324 fail2ban.filter : INFO  Found 52.14.24.93

В чем преимущество данного метода, например перед плагином для wordpress с аналогичным функционалом. Во первых вы снижаете нагрузку на сервер, поскольку заблокированный адрес уже не сможет соединится с вебсервером, а будет заблокирован на уровне межсетевого экрана (фаервола) сервера. Во вторых — у вас будет записан адрес атакующего в логах fail2ban, а значит вы сможете легко устроить ему вечный бан если он продолжит безобразничать.

Заключение

Такая нехитрая и эффективная в некоторых случаях защита у нас получилась. Я в течении дня собираю около тысячи попыток залогиниться через wp-admin. Не все боты долбятся 3 раза подряд и попадают в бан. Я бы даже сказал, большая часть этого не делает. Но они и не представляют опасности. Подобная этой настройка защитит в первую очередь от массового нашествия, которое способно серьезно замедлить работу сайта и хостинга в целом. Закрытие доступа на уровне iptables очень эффективный способ сохранить ресурсы сервера.

Помогла статья? Подписывайся на telegram канал автора

Рекомендую полезные материалы по схожей тематике:

Онлайн курс Основы сетевых технологий

Теоретический курс с самыми базовыми знаниями по сетям. Курс подходит и начинающим, и людям с опытом. Практикующим системным администраторам курс поможет упорядочить знания и восполнить пробелы. А те, кто только входит в профессию, получат на курсе базовые знания и навыки, без воды и избыточной теории. После обучения вы сможете ответить на вопросы:

  • На каком уровне модели OSI могут работать коммутаторы;
  • Как лучше организовать работу сети организации с множеством отделов;
  • Для чего и как использовать технологию VLAN;
  • Для чего сервера стоит выносить в DMZ;
  • Как организовать объединение филиалов и удаленный доступ сотрудников по vpn;
  • и многое другое.

Уже знаете ответы на вопросы выше? Или сомневаетесь? Попробуйте пройти тест по основам сетевых технологий. Всего 53 вопроса, в один цикл теста входит 10 вопросов в случайном порядке. Поэтому тест можно проходить несколько раз без потери интереса. Бесплатно и без регистрации. Все подробности на странице .

Важность своевременного обновления сервера — взлом centos сервера через уязвимость bash.
Эпидемия вируса шифровальщика vault — как защитить свои данные.

Базовая настройка centos для обеспечения минимальной защиты сервера.

Создание резервной копии сайта и ее хранение на Яндекс.Диске.

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *

Adblock
detector