Защита Asterisk или кубинская эпидемия

В последнее время началась большая волна взломов Asterisk с последующим прогоном через них траффика на кубу.

Поскольку минута звонка на кубу стоит в среднем от 1$ в минуту это может привести к печальным последствиям (за 17 часов на одном из транков баланс опустили до -8000$).
Схема работает так:

  1. Ищется в сети Asterisk сервер
  2. Подбирается список его пиров
  3. Подбираются пароли к пирам
  4. Аккаунт ставится в систему перебирающую транки при звонке.
  5. Набегает множество кубинцев звонящих через эту систему

Если купить доступ к такой системе и позвонить, то можно по задержке до гудка понять, что в этой схеме участвует огромное количество взломанных Asterisk серверов.

Подбор пиров

При подборе пиров используется метод реализованный в Sipvicious. Для сканирования перебираются пиры и анализируется ответ Asterisk. Например:

./svwar.py sip.somewhere
| Extension | Authentication |
-------------------------------
| 607 | reqauth |
| 606 | reqauth |
| 601 | reqauth |
| 600 | reqauth |
| 300 | reqauth |
| 900 | reqauth |
| 100 | reqauth |

Для продиводействия этому нужно включить директиву alwaysauthreject в sip.conf, которая при любых ошибках авторизации отвечает 401 Unauthorized.
После этого тот-же сервер при попытке сканирования будет отвечать 401 и утилита выдаст ошибку:

./svwar.py sip.somewhere
ERROR:TakeASip:SIP server replied with an authentication request for an unknown extension. Set --force to force a scan.
WARNING:root:found nothing

 

Кубинская проблема

Если ваши абоненты не собираются звонить на кубу, то ее надо закрыть в extensions.conf
Например:

;cuba
exten => _53.,1,Answer()
exten => _53.,n,PlayBack(vm-goodbye)
exten => _53.,n,Hangup()
;somali
exten => _252.,1,Answer()
exten => _252.,n,PlayBack(vm-goodbye)
exten => _252.,n,Hangup()

Можно конечно просто делать сразу Hangup, но данное действие потребует отключение нашего сервера из автоматической системы вручную, что не может не радовать.

P.S. Для проверки на то, что вы правильно прописали отклонение звонков на кубу можно попробовать позвонить по номеру +53997970. Это военная база и там всегда отвечает автоответчик.

Взято с Хабра — http://habrahabr.ru/blogs/voip/103341/

SipSak

sipsak is a small comand line tool for developers and administrators of SIP applications. It can be used for some simple tests on SIP applications and devices.

Features

  • sending OPTIONS request
  • sending text files (which should contain SIP requests)
  • traceroute (see section 11 in RFC3261)
  • user location test
  • flooding test
  • random character trashed test
  • interpret and react on response
  • authentication with qop supported
  • short notation supported for receiving (not for sending)
  • string replacement in files
  • can simulate calls in usrloc mode
  • uses symmetric signaling and thus should work behind NAT

Available for Linux, BSD & Win32

http://sipsak.org/

Asterisk SNMP

We needed a better way to monitor and track performance of RF.com‘s Asterisk 1.6 boxes.  We learned quickly that the scarce documentation for configuring Asterisk to use Simple Network Management Protocol (SNMP) is conflicting and outdated.  So we decided to share our configuration and hopefully save others a lot of time and head-scratching.

Downloading the Asterisk 1.6 source code

Enabling SNMP support in Asterisk requires a rebuild of Asterisk.

If you already have the Asterisk source code on your Asterisk server, open a terminal session with the Asterisk box and navigate to the Asterisk source code directory, then skip to Installing Net-SNMP.

If you don’t have the Asterisk source code on your Asterisk server, open a terminal session with the Asterisk box and copy these instructions to the command line:

#get asterisk source
# create source dir
mkdir -p /usr/src/digium
cd /usr/src/digium/
wget http://downloads.digium.com/pub/asterisk/asterisk-1.6-current.tar.gz tar xzvf asterisk-1.6-current.tar.gz
cd asterisk-1.6.*

Installing Net-SNMP

Asterisk SNMP support is provided by the res_snmp module.  To build this module, you need to install the following packages:

  • net-snmp
  • net-snmp-devel
  • net-snmp-utils
  • bzip2
  • bzip2-devel
  • lm_sensors
  • lm_sensors-devel
  • newt
  • newt-devel

On a CentOS or Fedora box you can use the following command to install all the packages at once:

yum -y install net-snmp net-snmp-devel net-snmp-utils bzip2-devel newt-devel lm_sensors-devel ; # snmp support – res_snmp

Preparing the Asterisk box

Once the necessary packages are installed, run the following commands from the Asterisk source code directory:

./configure
make menuselect

Running make menuselect will launch a menu that looks something like the image below.

Asterisk Module and Build Options Selection

Select the Resource Modules option from the menu and press the Return key.  Then scroll down to res_snmp, if res_snmp is not selected, press the spacebar to enable res_snmp.  The selection should now look like the image below.

Asterisk resource modules

If you are unable to select res_snmp, it means the Net-SNMP package was not installed properly or the Asterisk configure tool was unable to find the Net-SNMP package. Try running .configure -with-netsnmp from the command line and then re-run make menuselect.

Press x to save your configuration changes.

Now we can build Asterisk with SNMP support and install it by runing the following commands:

make /etc/init.d/asterisk stop ; # make sure asterisk is stopped before installing
make install

Configuring the SNMP daemon

There are three versions of SNMP, but two are insecure and should not be used over an untrusted network.  We chose SNMPv3, which requires authentication and encryption from the asteriskUser when it connects to the server.

To create an SNMPv3 user account and to configure it to require authentication and encryption, run the commands below, replacing change_this_password with your own password.

echo '# Asterisk user
rwuser asteriskUser priv
createUser asteriskUser SHA change_this_password AES
' >> /etc/snmp/snmpd.conf

Asterisk uses AgentX to communicate with the SNMP daemon.  Run the command below to configure the SNMP daemon for AgentX.  If your Asterisk daemon, does not run as a member of the asterisk group, replace asterisk in the agentXPerms command with an asterisk daemon group.

echo '
# Asterisk configuration
master agentx
agentXSocket /var/agentx/master
agentXPerms 0660 0550 nobody asterisk
' >> /etc/snmp/snmpd.conf

The commands below will install the Asterisk and Digium MIB files, configure the snmp daemon to start on boot, and launch the snmp daemon.

# copy asterisk mib files
cp doc/*-mib.txt /usr/share/snmp/mibs/

#start the snmpd daemon
chkconfig snmpd on
/etc/init.d/snmpd start

Let’s verify that the configuration is working so far by verifying that the snmp daemon set the file permissions correctly, run the following command:

ls -al /var/agentx

Your permissions must look like:

total 8
drwxr-xr-x  2 root   root     4096 Jan 31 18:01 .
drwxr-xr-x 20 root   root     4096 Jan 31 14:30 ..
srw-rw----  1 nobody asterisk    0 Jan 31 18:01 master

If the file permissions on /var/agentx and /var/agentx/master don’t allow the asterisk daemon group to write tomaster, Asterisk will not be able to communicate with the SNMP daemon. We had problems with the /var/agentx directory permissions, you may need to run the following command to fix the permissions.

chmod 755 /var/agentx

You can also check the logs to confirm that AgentX is running.

more /var/log/messages | grep snmpd

You should see lines like the following:

Jan 31 14:30:15 domU-12-31-39-00-55-E7 snmpd[27048]: Creating directory: /var/agentx
Jan 31 14:30:15 domU-12-31-39-00-55-E7 snmpd[27048]: Turning on AgentX master support.

Configuring the Asterisk res_snmp module

Now we configure Asterisk to use SNMP by running the following commands:

# configure res_snmp.conf
sed -e ‘s/;\(subagent\)/\1/’ -e ‘s/;\(enabled\)/\1/’ <configs/res_snmp.conf.sample >/etc/asterisk/res_snmp.conf

Start Asterisk from the command line:

asterisk -cvvvvvvvvvv

and look for the following Asterisk console output:

NET-SNMP version 5.4.1 AgentX subagent connected

The line above means that Asterisk is configured correctly and the res_snmp module has loaded.

You can now exit the asterisk console and then launch the Asterisk daemon, with the command below:

/etc/init.d/asterisk start

Final testing

You can now use the snmpwalk command to test that everything is configured correctly.  Replacechange_this_password with the password you created above for the snmp daemon configuration and run the commands below:

export MIBS=+ASTERISK-MIB
snmpwalk -v 3 -u asteriskUser -n “” -l authPriv -a SHA -A change_this_password -x AES -X change_this_password localhost asterisk

You should get a result like:

ASTERISK-MIB::astVersionString.0 = STRING: 1.6.0.5
ASTERISK-MIB::astVersionTag.0 = Gauge32: 10600
ASTERISK-MIB::astConfigUpTime.0 = Timeticks: (60776) 0:10:07.76
ASTERISK-MIB::astConfigReloadTime.0 = Timeticks: (60777) 0:10:07.77
...

Congratulations, you’ve finished and your Asterisk server is now configured to use SNMP.

Asterisk IP PBX ICQ Call Notification

(статью скоро переработаю, т.к. micq уже умер. 891rpm)

(АОН с Asterisk IP PBX на ICQ)

С 22 июня 2005 года работает у нас в службе тех-поддержки ICQ бот под ником Asterisk (UIN не скажу ).Занимается он тем, что по ICQ отправляет техподдержке номер телефона звонящего, дату и время.

Итак.
Имеем настроеный рабочий Asterisk на сервере.
Заходим на сайт http://www.micq.org/download.shtml.en и скачиваем последнюю версию mICQ
(на данный момент это mICQ 0.5.0.4 (released 2005-06-05)). То есть:

[roman@pbx1 log]$ cd ~
[roman@pbx1 ~]$ wget http://www.micq.org/source/micq-0.5.0.4.tgz
---bla-bla-bla---
[roman@pbx1 ~]$ tar -zxvf micq-0.5.0.4.tgz
---bla-bla-bla---
[roman@pbx1 ~]$ cd micq-0.5.0.4
[roman@pbx1 micq-0.5.0.4]$ ./configure --help #Читаем help если надо...
[roman@pbx1 micq-0.5.0.4]$ ./configure
---bla-bla-bla---
[roman@pbx1 micq-0.5.0.4]$ make
---bla-bla-bla---
[roman@pbx1 micq-0.5.0.4]$ su -
Password:
[root@pbx1 ~]# cd /home/roman/micq-0.5.0.4
[root@pbx1 micq-0.5.0.4]# make install
[root@pbx1 micq-0.5.0.4]# exit
[roman@pbx1 micq-0.5.0.4]$ micq

 

При запросе UIN смело набираем ‘0’ (просто ноль, кто не понял ) и жмем Enter. Далее придумываем архисложный пароль, вводим, Enter, вводим его еще раз, Enter, дальше если вы работаете через прокси , вводите его параметры, иначе, как все нормальные люди, смело жмете Enter.
Получаем UIN, регистрируемся на сервере.
Если хотите, в консоли mICQ есть команда ‘help’, а есть еще ‘help ‘, то есть что-то вроде ‘help msg’ даст вам справку по отправке сообщений.
Комманда ‘msg 227702532 Hello Anest!!! How are you today guy?’ спросит ‘Как дела?’ у нашего любимого Anest’а, а ‘msg 320598502 Privet rebyata! Pochemu na zvonki ne otvechaete?’ спросит у нашей техподдержки, что это она так расслабилась.
___________________________________________
# Дополнение от 03.07.2005г.
# В консоли mICQ дайте комманду
mICQ> autoaway 0
Changing status to away/not available after idling 0 seconds.
mICQ> save
Saving preferences to /home/roman/.micq/micqrc.
Your personal settings have been saved!

# Это не даст вашему боту эпизодически пропадать в offline.
___________________________________________
Поиграли, выходим из mICQ командой ‘exit’.
Далее:
[roman@pbx1 micq-0.5.0.4]# nano ~/.micq/micqrc

или другим вашим любимым редактором vi, pico, или просто по F4 в ‘mc’ на этом файле, меняем ‘ # password’ на ‘password <тут ваш пароль>’.
Продолжаем:
[roman@pbx1 micq-0.5.0.4]# screen -d -m micq

# Кто не пользуется и не знает, команда ‘screen’ создает нечто вроде виртуального терминала, от которого можно безболезненно отключаться, при этом программа, что запущена в нем, остается там работать в режиме S+, либо Ss+.
Почитайте ‘man screen’ и Краткое руководство по работе в SCREEN на www.opennet.ru.
# Проверяем, что заработало:
[roman@pbx1 micq-0.5.0.4]# ps ax | grep micq | grep -v grep
16046 ? Ss 0:00 SCREEN -d -m micq
16047 pts/2 Ss+ 0:00 micq

# Проверяем еще раз:
[roman@pbx1 micq-0.5.0.4]# screen -R
# Видим консоль mICQ, нажимаем Ctrl+c, потом отдельно ‘d’ — отключаемся от консоли.

Дальше правим конфиг Asterisk’a extentions.conf
[roman@pbx1 micq-0.5.0.4]# sudo nano /etc/asterisk/extensions.conf
# В нужном extention тепосредственно перед Dial вставляем нечто следующее:
exten => 4,7,System(/bin/echo -e "msg <тут UIN, на который хотим слать оповещение> 'Incoming Call From: ${CALLERIDNUM} To: <ваш номер> Received: ${DATETIME:0:2}/${DATETIME:2:2}/${DATETIME:4:4} at ${DATETIME:9}'" > /home/roman/.micq/scripting)
#Сохраняем файл, перезагружаем конфиги Asterisk’a
[roman@pbx1 micq-0.5.0.4]# su -
Password:
[root@pbx1 ~]# asterisk -r
pbx1*CLI> extensions reload
---bla-bla-bla---
pbx1*CLI> exit
[root@pbx1 ~]# exit
[roman@pbx1 micq-0.5.0.4]#

Все.
___________________________________________
# Дополнение от 19.07.2005г.
# Бот падает в оффлайн, если превышен некоторый лимит количества сообщений за единицу времени.
Слава Богу, обычно он сам поднимается после этого.
___________________________________________
___________________________________________
# Дополнение от 20.07.2005г.
# Дополнение к дополнению от 19.07.2005 🙂
Можно с некоторой периодичностью, например используя cron, скриптом давать боту комманду login.
___________________________________________
___________________________________________
# Дополнение от 16.03.2006г.
# Версия mICQ 0.5.0.4 с русским работала некорректно. Уже следующая работала отлично. На настоящий момент используйте версию 0.5.1.
http://www.micq.org/source/micq-0.5.1.tgz

# Про login
Добавьте в /etc/crontab
*/30 * * * * root echo "login" > /home/roman/.micq/scripting

# Про «зомбиков»
Если процесс micq умирает по какой-то причине (например кто-то сделал killall SCREEN), то в системе появляются подвисшие процессы ‘echo’, звонок не завершается нормальным образом.
Хак:
#!/bin/bash

# for pid in $(ps aux | grep "micq" | grep "scripting" | grep -v grep | awk '{print $2}'); do
for pid in $(ps aux | grep -v grep | awk '/micq|scripting/ {print $2}'); do
echo "Killing micq with PID $pid:"
kill -9 $pid
done
exit

# Дополнение от 02.08.2006г.
Автозапуск micq под пользователем roman.
Прописывается например в /etc/rc.d/rc.local
/bin/su — roman -c «/usr/bin/screen -d -m /usr/bin/micq»

http://asteriskforum.ru/viewtopic.php?p=1127

http://romik-g.livejournal.com/3690.html

FreeBSD. Полезные мелочи

Порты

Удобный поиск и установка

Иногда приходится сталкиваться с тем что не знаешь, где конкретно искать тот или иной порт для этого есть такая вещь как «whereis»
И чтобы совсем было удобно пустим по конвейеру те поставим точку с запятой «;»

и укажем что делать дальше «make config-recursive install clean», опция config-recursive позволяет сразу рекурсивно сконфигурировать все зависимости дабы не сидеть и не подтверждать каждый пакет
cd `whereis -q desktopbsd-tools`;make config-recursive install clean

Если собрали порт без поддержки какой нибудь опции, а нужно что то добавить или убрать, делаем следующее:

В диалоге настройки выбираем опции те что необходимы или убираем ненужные
cd /usr/ports/www/squid/ && make config

И собираем пакет
make FORCE_PKG_REGISTER=yes install clean
Что нужно обновлять?

Отобразить только необходимые программы для обновления.
/usr/sbin/pkg_version -v |grep ‘<‘

Или вот так:
pkg_version -vIL=
Демоны

Подсчет процессов занятых пользователем

ps -auxww | grep Raven2000 | wc -l
Железо

Скорость чтения HDD

dd if=/dev/ad4 of=/dev/null bs=1m count=1024
Какой процесс нагружает HDD

# top -m io -o total
Уборка

Уборка после пересборки ядра

Я создал себе такой файлик:
vi /uborka

#!/bin/sh
chflags -R noschg /usr/obj/usr
rm -rf /usr/obj/usr
cd /usr/src
make cleandir
make cleandir

chmod 777 /uborka

и после пересборки ядра просто запускаю его
/uborka

можно ещё удалить старое ядро:
rm -rf /boot/kernel.old

http://www.ignix.ru/node/72

FPing. Мониторинг сети.

Fping один из самых лучших инструментов для тестирования сети на основе icmp.В отличие от утилиты ping, fping можно легко использовать в скриптах, т.к вывод этой утилиты разрабатывался для парсинга. Можно написать несложные скрипты, которые будут посылать письмо в случае недоступности какого-то узла сети.

Для начала рассмотрим пример команд:

# fping router

Вывод:

router is alive

Можно дать утилите на съедение целый список серверов или ип из файла. Но опция -f джоступна только для root. Обычные пользователи могут делать следующим образом: Для примерна протестируем все хосты и ип из файла ~/.fping.conf

$ fping < ~/.ping.conf

Можно также сформировать диапозон тестируемых адресов на основе маски сети. Для примера протестируем сеть класса C 192.168.148.x:

$ fping -g 192.168.148.0/24
или
$ fping -g 192.168.148.0 192.168.148.255

Теперь рассмотрим небольшой скрипт, который посылает почтовое сообщение, если какой-то узел сети недоступен:

#!/bin/bash
HOSTS="router sun printer laptop sony-laptop xbox backup-server"
DLIST=""
for h in $HOSTS
do
fping -u $h >& /dev/null
if [ $? -ne 0 ]; then
echo ${h} host is down send email
# mail -s "Host ${h} down" admin@you.com

Другой пример:

#!/usr/bin/perl
$myHosts = ‘cat /etc/hosts.backup | fping -a‘;
foreach $host (split(/\n/,$myHosts)) {
# take action or call other function
}

IPtables )

Using iptables

The functionality of IP tables is derived directly from the networking subsystem of the Linux kernel, which accounts for the ability of Linux systems to efficiently process network traffic. The iptables command, which must be used with root privileges, simply provides an interface to this capability. The iptables tool is likely already installed on your Linux system; however, if it is not you can install this interface with your system’s package management tool. Nevertheless, theiptables examples in this document are intended to work with iptables running on top of contemporary versions of the Linux 2.6 Kernel.

The iptables Command

The iptables command provides a great deal of functionality; however, the syntax of this command is occasionally abstruse and difficult to comprehend. If you have difficulty understanding the iptables command, attempt to understand the general structure of an iptables directive rather than a deep understanding of the complete syntax. Consider the following example:

iptables -I INPUT -s 12.34.56.78 -j DROP

The -I option specifies the insertion of a rule at the beginning of the specified chain. Rules are applied sequentially so using the -I option will ensure that the above rule will be applied before all other rules. To append a rule to the end of a chain to allow all other rules to be processed first use the -A option in the following form:

iptables -A INPUT -s 12.34.56.78 -j DROP

In both commands, the -s option and the IP that follows specifies a source. The final -j option specifies a «target» or action to perform on the given packet. The target can specify handing the packet off to another chain, or as in this case a predefined action. Possible targets include the DROP target which drops the packet, the ACCEPT target that allows the packet go through as per normal, the RETURN target that allows the packet to continue to be filtered, and the QUEUE target that puts the packet in a queuing mechanism for further user-space manipulation.

At any point you can issue the following command to get a list of all current IP tables rules:

iptables -L

The iptables command is also capable of generating not only a list of the rules active on your system, but the number of packets that each output rule has «caught.» You can view this output with the following command:

iptables -L -nv

If you want to «flush» or clear all IP tables rules on your system, you may issue the following command:

iptables -F

Because iptables rules affect networking, it is possible to inadvertently prevent access to your system. If you have removed your ability to access your system directly and are connected to your machine over SSH, you may use an out-of-band console to recover access to your system. Exercise great care when instantiating new firewall rules.

When creating firewall rules, be aware that any rules created will not persist following your system’s next boot cycle. If you want to create persistent firewall rules, consider deploying a dedicated firewall package or inserting iptables commands in your system’s /etc/rc.local file.

iptables Rules

IP tables rules are processed serially in «chains» according to the kind of packet being processed. The system defines an INPUT chain which filters all incoming packets, a FORWARD chain which processes all packets that need to be redirected elsewhere, and an OUTPUT chain that can filter all outgoing packets. Users may define additional chains that rules in the default chains can filter packets through.

In addition to the chains upon which this document is primarily focused, iptables contains the concept of tables which allows the networking system to process different kinds of packets. The default table is the filter, which is the focus of this document and the core of the most used iptables functionality.

The following sections outline a number of basic approaches to creating a firewall and some common iptables rules. Combining these practical examples with the general knowledge provided above should allow you to construct your own network firewall and filtering system that is tailored directly to the needs of your deployment.

http://library.linode.com/security/firewalls/iptables

Asterisk. Запись телефонных разговоров.

Запись разговоров – довольно удобная вещь. Можно всегда прослушать кто, что кому говорил. Настройка не сложная, достаточно включить в dialplan на обработку этого направления функции Monitor или MixMonitor. Отличие этих функций заключается в том, что Monitor пишет раздельно голос звонившего и голос звонящего, в разные файлы. А MixMonitor создает один файл, который содержит оба направления разговора.

В диалплане это выглядит для Monitor так:

[dial]
exten => _8.,1,Set(fname=${STRFTIME(${EPOCH},,%Y%m%d%H%M)}-${CALLERID(number)}-${EXTEN})
exten => _8.,2,Monitor(wav,/home/share/monitor/${fname},mb)
exten => _8.,3,Dial(SIP/prov1)

В этом примере первой строчкой, Set(fname и т.д. мы описываем имя файла в котором будет хранится запись разговора. В нашем случае имя файла будет состоять из даты и времени когда происходил звонок, номера звонящего абонента и куда он звонил. Запись как я уже писал будет состоять из двух файлов в конце будут соответственно добавлены цифры 1 и 2 соответственно номерам каналов.

И второй пример – использование MixMonitor, тут все так же просто:

exten => _8.,1,Set(fname=${STRFTIME(${EPOCH},,%Y%m%d%H%M)}-${CALLERID(number)}-${EXTEN})
exten => _8.,2,MixMonitor(/home/share/monitor/${fname}.wav)
exten => _8.,3,Dial(SIP/prov1)

Тут все то же самое, только меньше флагов в команде MixMonitor, тут вписывается только имя файла с расширением.

Защита от брутфорса ssh, ftp, http: fail2ban

fail2ban анализирует логи, и если встречает последовательности, определяемые регулярными выражениям, применяет правила iptables

Ставим
apt-get install fail2ban

Конфигурируем
nano /etc/fail2ban/jail.conf

Указываем свой почтовый ящик для алертов
destemail = root@yourdomain.tld

Если есть необходимость, то можно в включить логирование пакетов, попавших в бан
banaction = iptables-multiport-log

По умолчанию, проверяется и банится только ssh
В секциях, которые нам необходимы ставим
enabled = true

Например:
[proftpd]

enabled = true
port = ftp,ftp-data,ftps,ftps-data
filter = proftpd
logpath = /var/log/proftpd/proftpd.log
maxretry = 6

Для VPS openvz:
на ноде делаем следующее:

cp /etc/fail2ban/action.d/iptables-allports.conf /etc/fail2ban/action.d/iptables-allports-vps.conf

Копируем строки содержащие INPUT, и в скопированном INPUT меняем на FORWARD
и меняем на vps
также, в actionstart добавим проверку на существование записей в цепочках, чтобы начальные правила не дублировались.

nano /etc/fail2ban/action.d/iptables-allports-vps.conf

[Definition]
actionstart = iptables -N fail2ban-vps
iptables -n -L fail2ban-vps | grep RETURN || iptables -A fail2ban-vps -j RETURN
iptables -n -L INPUT | grep fail2ban-vps || iptables -I INPUT -p <protocol> -j fail2ban-vps
iptables -n -L FORWARD | grep fail2ban-vps || iptables -I FORWARD -p <protocol> -j fail2ban-vps

actionstop = iptables -D INPUT -p <protocol> -j fail2ban-vps
iptables -D FORWARD -p <protocol> -j fail2ban-vps
iptables -F fail2ban-vps
iptables -X fail2ban-vps

actioncheck = iptables -n -L INPUT | grep -q fail2ban-vps
iptables -n -L FORWARD | grep -q fail2ban-vps

actionban = iptables -I fail2ban-vps 1 -s <ip> -j DROP
actionunban = iptables -D fail2ban-vps -s <ip> -j DROP

[Init]
name = default
protocol = tcp
port = anyport

nano /etc/fail2ban/jail.conf

bantime = 3600
maxretry = 10
banaction = iptables-allports-vps
port = anyport

[ssh-local]

enabled = true
port = ssh
filter = sshd
logpath = /var/log/auth.log

[1001-ssh]
enabled = true
filter = sshd
logpath = /vz/private/1001/var/log/auth.log

[1001-proftpd]
enabled = true
filter = proftpd
logpath = /vz/private/1001/var/log/proftpd/proftpd.log

[1002-ssh]
enabled = true
filter = sshd
logpath = /vz/private/1002/var/log/auth.log

[1002-proftpd]
enabled = true
filter = proftpd
logpath = /vz/private/1002/var/log/proftpd/proftpd.log

[1003-ssh]
enabled = true
filter = sshd
logpath = /vz/private/1003/var/log/auth.log

Теперь, при попытке перебора паролей на SSH или FTP, кулхацкеру будет закрыт TCP на все VPSы и ноду. Можно еще и UDP добавить, но в моем случае, в этом не было необходимости.

для проверки, реагиреут ли fail2ban на записи в логах можно воспользоваться утитлтой fail2ban-regex:

fail2ban-regex «line» «failregex»
fail2ban-regex /var/log/auth.log «Failed [-/\w]+ for .* from »
fail2ban-regex /vz/private/1002/var/log/auth.log /etc/fail2ban/filter.d/sshd.conf

Проверить конфигурацию
fail2ban-client -d

http://adminletters.blogspot.com/2009/07/ssh-ftp-http-fail2ban.html

Чеклист запуска сайта

Этот чеклист будет полезен всем, кто запускает сайты или следит за этим увлекательным процессом. Ничего не пропустите!

Перед запуском
Контент и стиль
Типографика
Корректные символы. Проставить корректные символы тире, кавычек и апострофов, в зависимости от языка сайта
Переносы слов. Проставить в важных местах неразрывные пробелы между инициалами, тире, перед последними словами
Для английского: Лигатуры. Проставить лигатуры в заголовках, если требуется
Вычитать тексты и проверить правописание
Связность текстов
Проверить регистр в важных текстах и заголовках
Обеспечить единый стиль текстов
Единство повторяющихся фраз (т.е. «Узнать больше», «Читать далее», «N комментариев» и др.)
Пунктуация в списках (напр. если пункт списка заканчивается точкой, следующий пункт должен начинаться с заглавной буквы и наоборот для точки-запятой)
Проверить, нет ли на сайте вшитых ссылок на dev-сервер (т.е. после запуска ссылки должны вести на сайт «в миру»)
Проверить, не осталось ли на сайте тестового контента
Проверить печатные версии важных страниц
Проверить RSS канал и отображение контента в Google Reader
При редизайне или изменении информационной архитектуры, проверить стоят ли редиректы со старых адресов разделов на новые
Проверить скрытые текст (т.е. alt/title атрибуты HTML тегов, тексты в JavaScript функциях)
Стандарты и валидация
Доступность для людей с ограниченными возможностями (не препятствуют ли нарушения восприятия цвета, звука и т.д. навигации по сайту)
HTML валидация
JavaScript валидация
CSS валидация
Доступность в поисковиках, SEO и статистика
Заголовки страниц очень важны; убедиться, что они осмысленны и содержат важные ключевые слова
Заполнить мета-тег description для важных страниц
Привести ссылки на главную страницу к единому виду (т.е. выбрать что-то одно из вариаций http://site.ru http://www.site.ru http://www.site.ru/index.html)
Гарантировать предыдущий пункт редиректом на выбранную версию (напр. редирект с http://www.site.ru/* на http://site.ru/*)
Убедиться в семантически-грамотном использовании HTML тегов (<h1><h2>, … и т.д.)
Проверить наличие важных ключевых слов в контенте
Привести формат ссылок к читабельному виду (напр. http://site.ru/blog/how-to-make-coffee, http://site.ru/user/vasya и т.д.)
Прикрутить Google Analytics, FeedBurner, и/или другие системы измерения статистики
Создать XML Sitemap
Добавить сайт в Google Webmaster Tools
Тестирование функциональности
Проверить весь заказанный/особый/сложный функционал
Проверить работу поиска (включая релевантность)
Проверить работу сайта в разных браузерах (Internet Explorer, Firefox, Opera, Safari, Chrome etc.), версиях (6, 7, 2.2, 3.1 etc.) и платформах (Windows, OSX, Linux)
Проверить вид сайта на разных разрешениях экрана (1280×1024, 1024×768, 1920×1200, 800×600…)
Протестировать все формы (контактов, комментариев, фидбека, …), поставить на них капчу или другую защиту
Проверить все e-mail шаблоны
Проверить работоспособность сайта с выключенным JavaScript, Flash, и другими компонентами
Проверить работоспособность внешних ссылок
Безопасность/Риски
Настроить бекапы по расписанию, и проверить восстановление из них.
Проверить нет ли у посетителей доступа к служебным/секретным/закрытым страницам
Закрыть поисковикам доступ к служебным/секретным/закрытым разделам сайта, используя robots.txt
Отключить вывод ошибок на экран
Проверить количество доступного дискового пространства и вычислить, на сколько его хватит
Настроить запуск регулярных процедур по крону (для большинства CMS)
Настроить email/SMS уведомления о неработоспособности сайта/сервера;
Производительность
Провести нагрузочное тестирование
Провести оптимизацию изображений/графики
Проверить и реализовать кэширование где это необходимо
Проверить общий размер/скорость загрузки страниц сайта
Минимизировать/сжать статику (JavaScript/HTML/CSS)
Оптимизировать CSS: короткие пути к изображениям; использовать «каскадную» природу стилей, и т.д.
Проверить наличие индексов в таблицах БД
Проверить другие настройки производительности на всех уровнях (Сервера, БД, CMS и т.д.)
Включить логи ошибок/производительности на сервере
Финальные штрихи
Создать свои страницы 404/403
Создать страницу «Сайт на обслуживании»
Создать favicon
После запуска
Маркетинг
Добавить сайт в социальные медиа: Twitter, ВКонтакте, LinkedIn, Facebook, и т.д.
Добавить сайт в поисковики
Настроить PPC/Google Adwords кампании, если требуется
Проверить форматирование сайта в результатах выдачи поисковиков
Другое
Мониторить фидбек (прямой с сайта, на Социальных Медиа, в выдаче Google и т.д.)
Отлавливать в статистике возможные проблемы с некоторыми разделами/страницами сайта
Обновлять контент

Взято тут: http://habrahabr.ru/blogs/webdev/65674/
Первоисточник здесь: http://drupaldance.com/blog/website-launch-checklist