Fail2ban server грузит процессор
Установил fail2ban, закоментил весь jail.conf и в jail.local сделал конф:
В /etc/fail2ban/filter.d/nginx-404.conf сделал регулярку по моим логам, в месте ip адреса в регулярку поставил конструкцию по аналогии с другими правилами.
Ребутнул fail2ban, в логе:
Зашел с чужого ip вызвал ошибку на которую срабатывает регулярка много раз подряд. ничего.
в логах соответствует записям типа
Еще столкнулся с проблемой, что try_files $1 =404 пишет в лог ошибок nginx, а return 404 в логах не появляется, не совсем понятно как однозначно маркировать директорию, чтобы она в логах была всегда, писать заведомо ложный try_files ?
Добавлено
Результат проверки регулярного выражения у меня выглядит так:
1. для тестов лучше поставить maxretry=1 , чтобы одного запроса было достаточно. 2. приведите и nginx-404.conf , и образцы записей из лога nginx , на которые fail2ban должен реагировать.
1 ответ 1
из приведённого образца:
видно, что для его идентификации необходимо и достаточно, по-моему, лишь наличие строки:
а для самого fail2ban -а нужен ещё ip-адрес, который ограничен фрагментами client: и , .
таким образом, строка с регулярным выражением должна выглядеть примерно так:
проверить, как fail2ban распарсит произвольную строку с произвольным регулярным выражением можно, воспользовавшись командой fail2ban-regex 'строка (из лога)' 'регулярное выражение' . вместо строки (из лога) можно указать и путь к лог-файлу (например, /var/log/nginx/error.log , а вместо регулярного выражения — путь к фильтру (например, filter.d/nginx-404.conf ).
пример с актуальными данными:
наиболее существенная (в данном случае) информация из отчёта:
в более новой версии fail2ban-regex поменялся формат вывода и добавились опции. в частности, надо добавить опцию -v , тогда на тех же данных существенной информацией будет:
где видно, что ip-адрес удачно извлечён, и:
где видно, что строка совпала с регулярным выражением: 1 matched
return 404 в логах не появляется
скорее всего, выполнение директивы return относится к «нормальному» завершению обработки запроса, и отчёт о её выполнении отправляется не в error_log , а в access_log .
если это верно, то можно завести отдельный location , в котором переопределить лог-файл, а в переменную logpath добавить этот файл:
а если понадобится ещё одно регулярное выражение, то можно добавить строку с ним примерно так:
Собственно, ЦПУ у тебя, наверно, i386DX или IBM Cloud, или Хасвел на Клоуд или i386 на SSD или AWE64 на PeniumIII.
void_ptr ★★★★ ( 27.09.14 21:38:07 )
Последнее исправление: void_ptr 27.09.14 21:38:27 (всего исправлений: 1)
да вроде core2duo 1.8
[irony_mode=off]А вообще-то о какой системе мы говорим?
Ты, наверное, студент. И твой преподаватель на экзаменах тебе ставит тройки, потому как все знания из тебя достает раскаленными клещами.
Повесь ssh на другой порт и убери fail2ban.
в общем /var/log/messages, на который был натравлен fail2ban был 127мб. Может от этого:) Поставил логротейт. Вроде полегчало. Топик пока не закрываю - посмотрю как будет.
bryak ★★. Доброе времени суток всем. Прошу подробнее описать как вы решили эту проблему? У меня так же Fail2ban грузить проц.
Ротацию логов сделай
мы где то год назад устали от fail2ban с его залюбонами по поводу проца (тяжкое наследие питона) и написал я свою систему обработки логов и реакции на регулярки. Интересно - опубликую.
Да я тоже перед тем, как заюзать fail2ban свой скрипт сделал и он работал, но если ротировать логи, то fail2ban нормально работает.
PS: конечно выкладывай, всем интересно будет.
1) убираешь fail2ban, вреда от него больше, чем пользы
2) запрещаешь вход ssh по паролю
3) делаешь ротацию логов
ну fail2ban не только ssh защищает. Он еще много чего делать умеет.
Если цель защитить ssh, то поможет и
Если цель защитить ssh, то помогает запрет входа по паролям, а не шаманство с попытками запретить вход.
Да я тоже перед тем, как заюзать fail2ban свой скрипт сделал
В action.d/iptables-multiport24 написано, в частности:
В /var/log/fail2ban.log строчки типа такой:
Но они продолжаются и в mail.log тоже, т.е. ничего не банится. Идея была, чтобы банил всю подсеть /24. Где что не так?
- Идея банить всю подсеть – ебанутая, не делай так.
- 185.36.81.242/24 – не адрес сети. Т.е. actionban и actionunban у тебя некорректны по своей сути.
Идея банить всю подсеть – ебанутая, не делай так.
Что в этом плохого? Они ж там с разных ip идут.
Ха! Это-то я понимаю :) Но там в коментах у fail2ban именно так советуется делать. Могу найти то место, где я такое нарыл :) И у самого fail2ban (см. выше) написано «127.0.0.1/24» Видимо он считает иначе :)
Что в этом плохого? Они ж там с разных ip идут.
На примере твоего ip из поста – 185.36.81.242 и вся подсеть 185.36.81.0/24 принадлежит облачному хостнгу где могут сидеть вполне нормальные клиенты которые должны иметь возможность достучаться до тебя (например почтовик твоего контрагента). Ты же банишь в том числе и его просто потому что в этой подсети засветился один спаммер…
BOOBLIK ★★ ( 29.01.20 12:26:32 )
Последнее исправление: BOOBLIK 29.01.20 12:28:03 (всего исправлений: 1)
которые должны иметь возможность достучаться до тебя
А, ну это-то очевидно. Я думал, имеется в виду нечто другое.
Ну ладно, а что не так, почему не банит-то? Поменял action просто на iptables-multiport - пока эффект ноль. Кстати, в логе fail2ban еще встречается такое:
Заменил. Пока вроде в логе только разные /24 адреса. Победа? Поглядим, что будет дальше.
Про «is not a JournalFilter instance» хотелось бы понять, что за ругань такая.
Про «is not a JournalFilter instance» хотелось бы понять, что за ругань такая.
Возможно что-то не то указано в logpath значении секции-описании postfix-rbl
Выложи сюда весь блок [postfix-rbl] из jail.local
Ура! Вроде, процесс пошел!
Хотя ничего не сказано про /24, но уже и то хорошо, что банить, вроде, начал.
Выложи сюда весь блок [postfix-rbl] из jail.local
На самом деле, он про все включенные для postfix секции так пишет. Вот секция SASL:
Кстати, вот про то, что в комментарии (про mail.warn) - это как чего конкретно сделать-то? И оно действительно стоит того? Абсолютный путь указать ему типа logpath = /var/log/mail.warn или что?
Абсолютный путь указать ему типа logpath = /var/log/mail.warn или что?
Да. У меня прописано:
Никаких ошибок нет.
Смотреть надо не в логах а выхлопе iptables-save
У меня сейчас наблюдается такая картина:
Вот такие пары строк с разными ip. Это как понять? Попробую убрать «/24» и использовать «стандартный» iptables-multiport. Не понимаю, правда, надо ли ему обнулять базу или можно просто подождать?
Насчет лога, вроде, там все ок, раз он находит строки из него. А вот это:
Смотреть надо не в логах а выхлопе iptables-save
что имеется в виду?
А как ты из ip адреса собрался выделить адрес сети?
И поменяй action на использование ipset. Ну или не меняй, но при ДДоСе от 10к участников, fail2ban на твоём action просто ляжет.
Ровно только то что написано. В логе может быть что угодно, реально он к работе netfilter не имеет отношения, если хотите убедиться что все действительно работает смотрите iptables-save а не логи.
И поменяй action на использование ipset
А как ты из ip адреса собрался выделить адрес сети?
В первом посте написано. Вычитал я это в коментах на самом fail2ban-е. И я выше уже отвечал, что не понимаю, как так можно указывать подсеть, но там так пишут. За что купил. ОК, я уже обратно поменял на стандартный muliport. Но эффект пока тот же. «WARNING already banned»
смотрите iptables-save а не логи.
А оно вообще ничего не показывает. Т.е. я так понимаю, оно должно показать текущие правила, а оно просто молча срабатывает и все.
И поменяй action на использование ipset
В общем, стер лог fail2ban и обнулил базу, после этого поставил:
Вроде, как начал банить, и никаких ошибок и предупреждений (типа, как было) не показывает. Но вырисовывается проблема общего характера - надо ставить большой findtime , поскольку адресов много, и повторяются они редко, но в пределах подсети /24 дело бы пошло быстрее, поскольку там ну очень много из одной и той же /24 подсети. Но как так сделать, чтобы банить всю подсеть, если, скажем, 10 адресов накопилось из нее, я в принципе не понял. Не обязательно же банить обязательно все 256, можно и по 64, например.
Или что, предлагаете просто смириться с таким положением дел?
Вроде, как начал банить, и никаких ошибок и предупреждений
Забей уже на лог fail2ban. чтобы проверить начал ты что-то банить или нет сделай iptables-save или ip6tables-save и посмотри что у тебя там в правилах появляется.
Но как так сделать, чтобы банить всю подсеть, если, скажем, 10 адресов накопилось из нее, я в принципе не понял.
Я сейчас попробовал своему iptables v1.6.0 скормить конструкцию вида -s 185.36.81.242/24 и как ни странно он не просто понял это, но и сам пересчитал за меня подсеть и внес правило вида -s 185.36.81.0/24. Так что бан по принципу описанному в ОП посте все же будет работать на свежих iptables.
но в пределах подсети /24 дело бы пошло быстрее, поскольку там ну очень много из одной и той же /24 подсети
Прелесть использования ipset в том, что у тебя в самом ipset может быть 254 отдельных адреса, а в iptables один –match-set src указывающий на этот сет и это будет работать так же быстро как и бан всей /24. Однако этот подход будет правильным в отличии от беспричинного бана /24 налево и направо.
p.s.: after 2 hours it drops to 44% then 31% now.
what's the source of this behavior?
The text was updated successfully, but these errors were encountered:
4. Restart Fail2ban.
Now that we have taken care of the log size issue, we can restart the Fail2ban service.
Hopefully, when the Fail2ban service restarts, it will go back to running normally instead of hogging your server’s CPU.
sebres commented Dec 17, 2014
python -c 'import gamin' will test only, if module (binding) was installed
7starsone commented Dec 17, 2014
I set backend = gamin
Could only initiated 'polling' backend whenever 'gamin' was requested
why if gamin is installed? i have to reboot the server?
7starsone commented Dec 18, 2014
maybe not?
what do you think about this htop screen. ?
load is under 2 on 8 cores. but that CPU 130% ? and why so many
/usr/bin/python /usr/bin/fail2ban-server -s /var/run/fail2ban/fail2ban.sock -p /var/run/fail2ban/fail2ban.pid -x -b
this is top after a reboot
what does mean that 125% from fail2ban-server?
yarikoptic commented Jan 5, 2015
On Mon, 05 Jan 2015, 7starsone wrote:
hi,
I don't know why but it seems unusable on CentOS 7.
The latest release is available now from packages updates.
it's fail2ban-0.9.1-2.el7.noarchthis package has old files from 28th October yet.
then, updated the files on
/usr/lib/python2.7/site-packages/fail2ban/client and . /server |
. /tests but
I have this on log:2015-01-05 16:02:57,148 fail2ban.server [11119]: INFO Changed logging target to /var/log/fail2ban.log for Fail2ban v0.9.1
2015-01-05 16:03:05,565 fail2ban.jail [11119]: ERROR 'Fail2BanDb' object has no attribute 'getCurrentBans'
yikes -- we don't even have this in our codebase:
$> git grep getCurrentBans || echo "nothing"
nothing
high cpu usage as before, 130%
why this app is not well tested on CentOS 7 and how to fix? where is
wrong?
see above and please close it back if you find it is indeed nothing to do with
the official release. If it is CentOS specific -- ask CentOS
maintainers.
Fail2ban is an excellent tool for preventing brute force SSH attacks. However, we have encountered a number of cases where Fail2ban was causing high CPU usage.
To make a long story short, this issue seems to happen when the auth.log file on Ubuntu becomes too large.
sebres commented Dec 18, 2014
That are threads, to hide it press shift+h (H).
- which growth has fail2ban.log (per second / minute)?
- can you look in fail2ban.log what all threads are doing (which rows appear en masse), example tail -F /var/log/fail2ban.log ?
- which growth has *.log, that are observed from f2b (per second / minute)?
- some services, that are observed from f2b, writes it log file with "DEBUG" mode (too much log entries)?
- have you possibly a DDOS atacke?
- If you not see something strange - can you possibly start it in DEBUG (config in /etc/fail2ban/fail2ban.local) and then look what f2b threads are doing (again which rows appear en masse)?
2. Remove the SQLite database.
After that, we are going to remove the temporary SQLite database that Fail2ban uses.
Don’t worry. Fail2ban will recreate this database once it restarts.
yarikoptic commented Dec 16, 2014
how big were the log files?
Fixing the high CPU usage.
After you have saved those changes to your /etc/logrotate.d/rsyslog file, you can use the following steps.
7starsone commented Dec 16, 2014
sebres commented Dec 17, 2014
@7starsone Which backend will used from you? (in config it is auto , so please see in fail2ban.log)
sebres commented Dec 17, 2014
Also we have polling , I think f2b should be really updated to newest version, can you install/update it manually?
I don't know why gamin cannot be initialized on your host. Possibly missing gamin-python binding? Try this:
sebres commented Dec 18, 2014
7starsone commented Dec 18, 2014
here it stays for a while.. i don't think nothing abnormal. this is with loglevel = NOTICE
then, with loglevel = DEBUG
you can find my log here [edited]
7starsone commented Dec 18, 2014
then it starts again. here it's a mess
I think that this version is not well tested on CentOS 7.
completely removed that test version and reinstalled from epel.
it works better and bans as usual. while on the new version it does really few after the start. e.g. it didn't ban sshd, never.
anyway the htop now is:
maybe found the issue:
I'm running Virtualmin
access and error logs are in /var/log/virtualmin/
and it doesn't logrotate them, they are huge.
2GB . 200MB. and so on. i will ask support on Virtualmin
thanks
7starsone commented Dec 18, 2014
yes, was active. next time first stop it and then update? those patches are enough ATM ? thanks
logrotate only rotates the auth.log file every week.
If your server witnesses a spike in SSH attempts, then the auth.log file will grow in size.
However, logrotate will not rotate this file every day. Instead, it will only rotate it once per week.
In some cases, the auth log will swell in size because of an increase in SSH activity. As a result, Fail2ban can run into difficulties.
1. Stop the Fail2ban service.
Firstly, we are going to stop the Fail2ban service while we do a “clean up”.
sebres commented Dec 18, 2014
one more thing: if you disable individually each jail after other, in particular recidive , will it settled down?
You can also try to set it idle:
7starsone commented Jan 5, 2015
hi,
I don't know why but it seems unusable on CentOS 7.
The latest release is available now from packages updates.
it's fail2ban-0.9.1-2.el7.noarch now
this package has old files from 28th October yet.
then, updated the files on /usr/lib/python2.7/site-packages/fail2ban/client and . /server | . /tests but
I have this on log:
updated:
actions.py | database.py | datetemplate.py | filter.py | filtersystemd.py and so on.
high cpu usage as before, 130%
why this app is not well tested on CentOS 7 and how to fix? where is wrong?
thank you
7starsone commented Dec 17, 2014
ATM on CentOS 7 is
yum update fail2ban --enablerepo=epel-testing
for fail2ban.noarch 0.9.1-2.el7
Rotate auth.log on a daily basis.
The first step towards fixing this issue is to configure logrotate to rotate the auth file on a daily basis instead of a weekly basis.
On Ubuntu, the logrotate settings for the auth.log file are in the following file.
By default, the auth.log settings will share the same settings as mail.info, cron.log and mail.warn, etc.
However, you will need to remove /var/log/auth.log from that list and give it a separate configuration block.
Here, you can see that auth.log has its own configuration block. You can also see that we are using daily instead of weekly.
We also added “su root syslog” to the settings. If this line is not present, logrotate will throw an error when we manually run it. This error will say that the parent directory does not have the correct permissions.
7starsone commented Dec 18, 2014
the problem is the PID of recidive. indeed
or better, I don't know if is a real "problem", the system is responsive anyhow.
if I do fail2ban-client set recidive idle on it returns True but does nothing.
here is my recidive in jail.local
now I try to disable recidive. but why this happens?
If I stop fail2ban in this situation, instead, the problem is real 'cause it takes too much time to stop and load average goes even up 7+ .
p.s.: my error, it has nothing to do with recidive alone, even with it disabled that main fail2ban server thread is at 130% (even if sleeping most of the time, so can't understand)
7starsone commented Dec 18, 2014
updated, patched actions.py, database.py, databasetestcase.py, action_checkainfo.py
service fail2ban restart
is it normal? something else to do?
thank you
3. Manually force logrotate to rotate the auth.log file.
At this stage, we are going to manually run logrotate and tell it to rotate the auth.log file.
For some of the other log files, you might see a few errors about the parent directory not having the correct permissions. However, the main thing is that you do not see this error for auth.log.
Once the command is finished running, the auth file should be much smaller in size.
sebres commented Dec 17, 2014
- save your current insallation (best backup all, at least config, init, runtime files (example for debian):
But this all without any warranty - I have never tested it for centos.
sebres commented Dec 18, 2014
I understand it correctly - during the update the fail2ban was active? If it is so, just ignore it this time once.
7starsone commented Dec 18, 2014
issue solved, ATM the default fail2ban for CentOS 7 is good enough. then I will update when it will be available on epel
the problem was logrotation, the log files were HUGE, really. and I fixed it ;-)
thank you very much
7starsone commented Dec 17, 2014
how can I update fail2ban on CentOS 7, please?
then, I had to
yum install gamin-python
so, is not enough to install gamin ? and I also did python -c 'import gamin' but I would like to know.
the correct steps are
OR something of those is not needed?
anyway, now seems that gamin is working. but is it better than polling?
why the real difference is not explained anywhere?
thanks
7starsone commented Dec 17, 2014
what I have to look in fail2ban.log? mine is set to NOTICE now, to avoid my IP to be shown when ignored.
i have to use gamin on CentOS ?
..but why guys from CentOS don't release your updates?
thank you
p.s.: yum installed gamin. then I restarted the fail2ban service, so as I know it should use gamin even if on auto. (or i have to set it manually, anyhow?) then at start it consumes almost 110% CPU with
2 processes and it takes much time.
/usr/bin/python /usr/bin/fail2ban-server -b -s /var/run/fail2ban/fail2ban.sock -p /var/run/fail2ban/fail2ban.pid -x
Читайте также: