Wednesday, November 7, 2012

Борьба с DDoS атаками средствами iptables и sysctl


Сегодня я попытаюсь привести пример конфигурации фаервола, а также оптимизации системных настроек для повышения устойчивости сервера к так называем атакам типа «отказ в обслуживании».
Информации в поисковиках на эту тему море, но, как обычно, это или малограмотные или очень разрознененные и не сведённые в одну схему примеры.
Ниже приводится листинг разрешительной (не такой жёсткой как запретительная) политики настройки iptables, а также пример оптимизации настроек sysctl. В результате будет ограничено количество одновременных подключений с одного ip адреса на порт веб-сервера, сервера DNS, а также ограничено количество подключений к службе ssh (3 подключения за 5 минут с одного ip-адреса). Будет реализована защита от спуфинга на уровне файрвола, а также на уровне ядра.

Хорошее развёрнутое русское руководство по iptables с подробным разъяснением принципов его работы и примерами использования (некоторые из которых используются чуть ниже) можно найти в статье iptables на Википедии (sic!), а про sysctl тут http://debian.telenet.ru/doc/sysctl.conf


# БОРЬБА С DDOS
 
iptables -N ssh_brute_check # Создаем цепочку для проверки попыток соединений на защищаемый порт
# Если за последние 5 минут (300 секунд) с одного адреса было 3 или более новых соединений — блокируем этот адрес
iptables -A ssh_brute_check -m conntrack --ctstate NEW -m recent --update --seconds 300 --hitcount 3 -j DROP
# В противном случае — разрешаем, и при этом заносим в список
iptables -A ssh_brute_check -m recent --set -j ACCEPT
iptables -F INPUT # Очищаем цепочку INPUT
iptables -A INPUT -m conntrack --ctstate ESTABLISHED,RELATED -j ACCEPT # Разрешаем пакеты по установленным соединениям
# Все попытки открыть новое соединение по SSH направляем на проверку
iptables -A INPUT -m conntrack --ctstate NEW -p tcp --dport 22 -j ssh_brute_check
# Здесь можно разрешать те порты, для которых такая проверка не нужна. Например, HTTP
iptables -A INPUT -m conntrack --ctstate NEW -p tcp --dport 80 -j ACCEPT
iptables -P INPUT ACCEPT
 
 
# позволяет узнать сколько одновременных подключений на порт с 1 айпи
# netstat -plan | grep :80 | awk '{print $5}' | awk -F: '{print $1}' | sort | uniq -c
# netstat -ntu | awk '{print $5}' | cut -d: -f1 | sort | uniq -c | sort -n
 
# устанавливаем максимальное количество подключений с одного айпи.
# В браузерах эта количество подключений к серверу ограничено 16 соединениями,
# но стоит учитывать тех, кто сидит за NAT, а также что пользователь
# может открыть 2 сайта на разных айпишниках одного и того же сервера.
# Данный параметр подбирается оптимально с помощью предыдущей команды.
iptables -A INPUT -p tcp --dport 80 -m connlimit --connlimit-above 32 -j DROP
iptables -A INPUT -p tcp --dport 80 -j ACCEPT
# то же для DNS
iptables -A INPUT -p udp --dport 53 -m connlimit --connlimit-above 8 -j DROP
iptables -A INPUT -p udp --dport 53 -j ACCEPT
 
# будет препятствовать спуфингу от нашего имени.
# Ведь если мы получаем пакет с установленными флагами SYN и ACK
# (такой комбинацией флагов обладает только ответ на SYN-пакет) по еще не открытому соединению,
# это означает, что кто-то послал другому хосту SYN-пакет от нашего имени, и ответ пришел к нам.
# Конечно, злоумышленнику предстоит еще угадать номер последовательности.
# Согласно приведенному правилу, наш хост ответит RST-пакетом, после получения которого
# атакуемый хост закроет соединение.
iptables -I INPUT -m conntrack --ctstate NEW,INVALID -p tcp --tcp-flags SYN,ACK SYN,ACK -j REJECT --reject-with tcp-reset
 
# Для защиты от SYN атак включаем SYN-cookies
sysctl -w net.ipv4.tcp_syncookies=1
# Увеличиваем размер очереди полуоткрытых соединений (также полезно при SYN флуде) (default 512)
sysctl -w net.ipv4.tcp_max_syn_backlog=4096
# Проверять TCP-соединение каждую минуту. Если на другой стороне - легальная машина, 
# она сразу ответит. Дефолтовое значение - 2 часа.
sysctl -w net.ipv4.tcp_keepalive_time=60
# Повторить пробу через десять секунд
sysctl -w net.ipv4.tcp_keepalive_intvl=10
# Количество проверок перед закрытием соединения
sysctl -w net.ipv4.tcp_keepalive_probes=5
# Фильтр обратного пути, защита от спуфинга (подмены адресов)
sysctl -w net.ipv4.conf.default.rp_filter=1
# Уменьшение времени удержания «полуоткрытых» соединений
# Сделаем так, чтобы перепередача осуществлялась на 3 секунде
# и  полное время хранения полуоткрытых соединений в очереди составило 9 секунд
sysctl -w net.ipv4.tcp_synack_retries=1
# Изменяем время ожидания приема FIN до полного закрытия сокета
sysctl -w net.ipv4.tcp_fin_timeout=10

Защита от DDOS атаки подручными средствами

За последнее время, наш сайт часто подвергается достаточно мощным DDOS атакам, к слову последняя атака была самой крупной за последнее время, размер ботнета по нашим оценкам — около 10 тысяч машин, мощность — 100 Mbits/s.

Атаку заметила даже Лаборатория Касперского, и предложила свою помощь в отражении, за что им спасибо. Правда к тому времени мы самостоятельно нашли решение, которое блокирует атаку. Собственно про это решение и пойдет речь.

Все началось в прошлую пятницу в пять часов вечера, и продолжалось до обеда в понедельник. Выходные прошли, за увлекательным занятием по отстрелу ботов. Пришлось немного попотеть, пока нашлось рабочее решение для противодействия атаке.

Атака была типа HTTP Flood. Система на которой у нас работает сайт — Apache под Linux. Мы написали несколько скриптов, которые будут приведены в тексте статьи. В принципе аналогичный подход можно применять и для Windows/IIS.

Попытаюсь рассказать, какие основные шаги мы сделали для отражения атаки, и какие проблемы возникали по ходу:

Получение доступа к своему серверу


Из за высокой нагрузки, вызванной атакой, подключение к серверу становится невозможным. Выход — перезагрузка, плюс хорошая реакция, чтобы попытаться подключится к перезагруженной машине, и отключить сервис, на который производится атака, и провести анализ атаки. Но при мощной атаке, даже после перезагрузки, подключение очень проблематично. Иногда приходилось перезагружать сервер по нескольку раз, пока удавалось залогинится в систему.

После того как получилось зайти в систему, и выключить апач (service httpd stop) нужно убрать запуск апача при старте системы. Это даст возможность получить доступ к машине с помощью перезагрузки, если что-либо пойдет не так. Делается это с помощью команды:

# chkconfig httpd off

Решение не идеальное, но для начала пойдет.

Автоматическая блокировка атакуемого сервиса при высокой загрузке системы


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

После некоторых раздумий был найден выход. При возрастании загрузки выше, некоторого критического уровня, блокировать файрволом атакуемый сервис (в нашем случае 80-й порт).

Собственно был написан универсальный скрипт который делает задуманное. Вызов скрипта следующий:

# blockOnHighLoad.sh turnOn80Port 5 turnOff80Port

Скрипту передаются две команды, и максимальный уровень загрузки системы при котором нам нужно что-либо предпринять. В данном случае при достижении load average значения 5, запускается команда, которая перекрывает файрволом 80-й порт. При возвращении загрузки на нормальный уровень, порт снова открывается.

Собственно говоря, для простых случаев, можно действия описывать прямо при вызове, например, предыдущая команда без использования внешних скриптов:

blockOnHighLoad.sh "/sbin/iptables -D INPUT -p tcp -m tcp --dport 80 -j DROP" 5 "/sbin/iptables -A INPUT -p tcp -m tcp --dport 80 -j DROP"

Т.е. мы напрямую блокируем/разблокируем порт с помощью iptables.

В более сложных случаях, например, когда атака идет на несколько сервисов сразу, или нужно выполнить сразу несколько шагов, можно использовать внешние команды.

Так наряду с блокировкой единственного порта, полезно бывает полностью «закрыть» машину, оставив только порт для подключения по SSH. Такое действие целесообразно проводить при «уходе» загрузки в «космос». Вот вторая полезная команда:

blockOnHighLoad.sh "" 50 "blockAllExcept.sh 22"

Тут по достижении значения load average в 50 единиц, мы закрываем все что можно, за исключением SSH (22-й порт). Открытие порта производится в данном случае в ручном режиме.

Теперь осталось это все хозяйство вставить в автозагрузку системы. Плюс нужно запустить выключенный httpd. Для этого мы дописали следующие команды в скрипт инициализации /etc/rc.local:

blockOnHighLoad.sh "/sbin/iptables -D INPUT -p tcp -m tcp --dport 80 -j DROP" 5 "/sbin/iptables -A INPUT -p tcp -m tcp --dport 80 -j DROP" >> /var/log/blockOnHighLoad-5-80.logs  2>&1 &
blockOnHighLoad.sh "" 50 "blockAllExcept.sh 22" >> /dev/null &
service httpd start

Почему не оставить нормальный запуск httpd через системный старт сервисов? Потому что он запустится перед автоблокировщиком, и при «хорошей» атаке сразу положит систему и скрипт инициализации может не выполнится.

Отмечу, что скрипт печатает небольшой диагностический лог. Выводятся сообщения, когда происходит переключение «режима» работы и печатается текущая загрузка и режим. В
примере выше, этот лог сохраняется в файл /var/log/blockOnHighLoad-5-80.logs. Так что можно посмотреть историю.

Что дальше?


После того как мы получили доступ к машине, мы провели анализ атаки, написали скрипт который автоматически банит ботов. Тут стоит отметить, что при количестве блокируемых IP более нескольких сотен, вариант с iptables, не проходит. Потому как iptables крайне не эффективно работает с большими списками. iptables нужно использовать в связке с ipset, который как раз заточен на хранение и поддержку больших списков IP для iptables. Почитать про детали можно в этой статье.

Надеемся что наш опыт поможет в борьбе с атаками.

Спасибо за внимание.

Собственно скрипты:

blockOnHighLoad.sh
#!/bin/bash

state=normal
i=0
while [ 1 ]; do

        up=`uptime`
        loadavg=`echo $up | sed 's/.*average: //' | sed 's/,.\+//' | sed 's/\..\+//'`

        i=$(($i+1))
        if ((  $i > 60 )); then
                echo
                echo -n `date` " "
                i=0
        fi

        if (( $loadavg > $2 ));then
                if [ "$state" == "normal" ];then
                        state=high
                        echo
                        echo `date` HIGH $3
                        $3
                else
                        echo -n ${loadavg}H
                fi
        else
                if [ "$state" == "high" ];then
                        state=normal
                        echo
                        echo `date` Normal $1
                        $1
                else
                        echo -n ${loadavg}.
                fi
        fi
        sleep 1
done


blockAllExcept.sh (Скрипт взят отсюда)
#!/bin/sh
# Minimal emergency firewall (block everything except SSH).
iptables -P INPUT ACCEPT
iptables -P OUTPUT ACCEPT
iptables -P FORWARD ACCEPT
iptables -F
iptables -X
iptables -A INPUT -p tcp -m tcp --dport $1 -j ACCEPT
iptables -P INPUT DROP
iptables -A OUTPUT -p tcp -m tcp --sport $1 -j ACCEPT
iptables -P OUTPUT DROP

Useful Cron Alternatives For Linux

Anacron is a periodic command scheduler just like cron. The only difference is that it does not need your computer to be always running. You can schedule your task to run at any time. When your computer is off, the task will be executed the next time you turn the computer on.
To get started, simply install anacron in your system. It is available in most package managers. Use the following command to install in Ubuntu:
sudo apt-get install anacron
Anacron works similar to cron. You can add your job to the /etc/anacrontab file.
The syntax to add a job is
period   delay-after-computer-start   job-identifier   command
For example, to run a backup script everyday, you can add the following command:
1   15    cron.daily     /bin/sh /home/damien/backup.sh
The disadvantage of anacron is that it only deals with tasks on a daily, weekly or monthly schedule. You can’t use it for a hourly or minutes schedule.
Fcron is the best of both cron and anacron. It doesn’t require your computer to be running 24×7, and it can work with tasks on an hourly or minute basis.
The only way to install Fcron is to download the source file and compile it yourself.
1. Download the source file here.
2. Extract the archive. Open a terminal and change the filepath to the extracted archive folder.
3. Run the following commands:
./configure
make
sudo make install
It will ask you a few questions during the installation and you can safely answer “y” (yes) for all of them.
To start creating a fcron job, simply type fcron -e in the terminal.
The syntax for fcron is similar to cron:
minute  hour  day-of-month  month  day-of-week  command-to-be-executed
and it comes with more options than cron, such as setting up a task to run between a time range.
For those who prefer a GUI, you can check out fcronq
Hcron is relatively unknown, but that does not make it less useful. In fact, it comes with several features that make it unique. For example, you can easily label and organize your cron type jobs, manage a network of computers and your users’ crontab files, beck up easily, and version control your cron type jobs. The only drawback is that it has not been updated since 2010.
To install hcron, download the .deb file and install it in your system. For distro that are using rpm, you can easilyconvert the deb file to rpm.
Hcron stores each event as a plain text file. To get started, simply create a text file with the command:
hcron-event /path/to/event-file.txt
In the text editor that opens, you can fill in the details of the event.
There are many more things that you can do with hcron and it is advisable to download the user guide to have a better understanding of how it works.
Jobber is a task scheduler written in GO and is a more powerful tool than cron. It features job execution history with status, controlling whether and when a job is run again after it fails and getting notified on each failed run or only about jobs that were disabled due to repeated failures.
To install Jobber, you have to make sure that GO is installed in your system. Next, type the commands:
cd /path/to/your/go/workspace
go get github.com/dshearer/jobber
make -C src/github.com/dshearer/jobber
After the installation, start Jobber with the command:
sudo /usr/local/sbin/jobberd start
To create jobs, create a file named “.jobber” in your home directory and add the job in the following format:
- name: #Enter the job name here
  cmd: #the command to run
  time: #as the same as cron format
  onError: #Stop | Backoff | Continue
  notifyOnError: #false | true
  notifyOnFailure: #false | true
As you can see from the format, it allows you to define the actions to take when it has errors (“Stop”, “Backoff” or “Continue”) and whether it should notify you when it fails.
Once you have updated the job list, use jobber reload to get Jobber to reload the new list.
At any time, you can use jobber log to see a list of recent runs of any jobs.
Cron is widely available and easy to use, but when it doesn’t work as you require, you might be better off using a replacement app. The cron alternatives above are more powerful than cron and should fulfill your needs. If you know of other cron replacement apps that are not mentioned above, feel free to let us know in the comments below.

Отказоустойчивый кластер на Ubuntu

Кластер – это набор независимых компьютеров, работающих совместно для повышения доступности служб и приложений. Кластеризованные серверы (называемые узлами) соединены друг с другом с помощью кабелей и программного обеспечения. В случае отказа одного узла предоставлять услугу начинает другой узел, используя процесс, называемый перемещением.Отказоустойчивые кластеры (High-availability clusters, HA, кластеры высокой доступности) создаются для обеспечения высокой доступности сервиса, предоставляемого кластером. Избыточное число узлов, входящих в кластер, гарантирует предоставление сервиса в случае отказа одного или нескольких серверов. Типичное число узлов — два, это минимальное количество, приводящее к повышению доступности. Создано множество программных решений для построения такого рода кластеров.
Что получим: Два сервера объединённых в кластер, при том что каждый из них (UbuntuServer1 и UbuntuServer2) будет считать себя резервным (делаем это осознанно, чтобы в обычном режиме работы, запросы обрабатывали оба сервера, каждый по своему ip, а в случае отключения одного из серверов, работающий будет обрабатывать запросы к первому и второму серверам). В случае падения «псевдо основного» на резервном поднимался ip адрес «псевдо основной» ноды кластера. Тоесть при падении одного из серверов, другой сервер возьмёт обслуживание запросов «упавшего» сервера на себя. Между серверами будет организован drbd в режиме primary-primary, тоесть на каждом из серверов будут актуальные данные, файлы пользователей (раздел home), а режим primary-primary позволит монтировать эти разделы на каждом из нод. На каждом сервере будет по два жёстких диска (виртуальных), один под сиситему, второй под блочное устройство drbd на котором распологаться будет home.
Так же вместо использования drbd можно использовать распределённую реплицируемую  файловую систему GlusterFS.
1. Установка Ubuntu (на двух серверах).
Установка системы производиться в серверном варианте, без рабочих столов и X-сервера. После чего производиться доустановка всех необходимых пакетов для работы сервера и выполнения его основных функций.
UbuntuServer1:
eth0 10.250.30.201/24 (для подключения к нему пользователей, осн работы)
 
eth1 10.0.3.201/24 (для HeartBeat)
UbuntuServer2:
eth0 10.250.30.205/24 (для подключения к нему пользователей, осн работы)
 
eth1 10.0.3.205/24 (для HeartBeat)
2. Организация кластера с помощью Heartbeat
1. Установка heartbeat
$ sudo apt-get install heartbeat
2. Настройка heartbeat
В /etc/ha.d/authkeys добавляем:
auth 2
2 sha1 password
Затем назначаем разрешения на чтение этого файла только для пользователя “root”:
root@UbuntuServer1 ~# chmod 600 /etc/ha.d/authkeys
 
root@UbuntuServer2 ~# chmod 600 /etc/ha.d/authkeys
В файл /etc/ha.d/ha.cf (на обоих серверах), добавим:
autojoin none
 
logfacility local0
 
udpport 694
 
bcast (eth0) eth1
 
keepalive 40ms
 
warntime 1
 
deadtime 2
 
#initdead 10
 
auto_failback on # при восстановлении «упавшего» сервера адрес вернуть
 
node UbuntuServer1 # в /etc/hosts должны быть прописаны оба сервера, на серверах
 
node UbuntuServer2 # 10.0.3.201 UbuntuServer1, 10.0.3.205 UbuntuServer2 см. uname -n
 
respawn hacluster /usr/lib/heartbeat/ipfail
 
use_logd yes
 
debugfile /var/log/ha-debug
 
logfile /var/log/ha-log
Создадим файлы для логов heartbeat на обеих нодах:
root@UbuntuServer1 ~# touch /var/log/{ha-log,ha-debug}
 
root@UbuntuServer2 ~# touch /var/log/{ha-log,ha-debug}
Добавляем Heartbeat в запуск при старте системы (если chkconfig нет в системе его можно установить apt-get install chkconfig):
root@UbuntuServer1 ~# chkconfig --level 2345 heartbeat on
 
root@UbuntuServer2 ~# chkconfig --level 2345 heartbeat on
Редактируем/создаём файл /etc/ha.d/haresources
для UbuntuServer1:
UbuntuServer2 Ipaddr::10.250.30.205/24 "здесь можно указать разделяемую службу"
для UbuntuServer2:
UbuntuServer1 Ipaddr::10.250.30.201/24 "здесь можно указать разделяемую службу"
В соответствии с этими настройками на «псевдо-резервном» сервере будет подниматься интерфейс упавшего, и «разделяемая» служба.
3. Установка и настройка блочного сетевого устройства (DRBD) для создания RAID1 по сети.
Как показала практика при высокой нагрузке на реплецируемую распределённую систему хранения данных, лучше использовать в случае с кластером серверов — GlusterFS, а не связку drbd+ocfs2, так как она даёт меньшую нагрузку на систему.
3.1. Установка DRBD
$sudo apt-get install drbd8-module-source drbd8-utils (на обоих серверах)
3.2 Настройка DRBD
Смотрим какой раздел у нас под блочное устройство:
$sudo fdisk -l
(на обоих серверах)
В нашем случае /dev/sdb
Создаём раздел на /dev/sdb (на обоих серверах):
$sudo fdisk /dev/sdb
 
Device contains neither a valid DOS partition table, nor Sun, SGI or OSF disklabel
 
Building a new DOS disklabelwith disk identifier 0x882944df.
 
Changes will remain in memory only, until you decide to write them.
 
After that, of course, the previous content won't be recoverable.
 
The number of cylinders for this disk is set to 20480.
 
There is nothing wrong with that, but this is larger than 1024,
 
and could in certain setups cause problems with:
 
1)software that runs at boot time (e.g., old versions of LILO)
 
2)booting and partitioning software from other OSs
 
(e.g., DOS FDISK, OS/2 FDISK)
 
Warning: invalid flag 0x0000 of partition table 4 will be corrected by w(rite)
 
Command (m for help):<-- n
 
Command action
 
e extended
 
p primary partition (1-4)<-- p
 
Partition number (1-4):<-- 1
 
First cylinder (1-20480, default 1): <-- ENTER
 
Using default value 1
 
Last cylinder or +size or +sizeM or +sizeK (1-20480, default 280480): <-- ENTER
 
Using default value 20480
 
Command (m for help):<-- t
 
Selected partition 1
 
Hex code (type L to list codes):<-- 83
 
Command (m for help):<-- w
 
The partition table has been altered! Calling ioctl() to re-read partition table. Syncing disks.
Теперь на каждом из серверов есть раздел /dev/sdb1
Конфигурируем сам DRBD (на двух серверах):
$sudo nano /etc/drbd.d/global_common.conf
 
global {
 
usage-count no; он-лайн статистика на сайте разработчиков откл.
 
}
 
common {
 
protocol C
 
}
 
resource r0 {
 
startup {
 
become-primary-on both;
 
}
 
net {
 
allow-two-primaries;
 
cram-hmac-alg sha1;
 
shared-secret "123456";
 
after-sb-0pri discard-zero-changes;
 
after-sb-1pri discard-secondary;
 
after-sb-2pri disconnect;
 
rr-conflict violently;
 
}
 
syncer {
 
rate 40M;
 
}
 
on UbuntuServer1 {
 
device /dev/drbd0;
 
disk /dev/sdb1;
 
address 10.0.3.201:7789;
 
meta-disk internal;
 
}
 
on UbuntuServer2 {
 
device /dev/drbd0;
 
disk /dev/sdb1;
 
address 10.0.3.205:7789;
 
meta-disk internal;
 
}
 
}
В /etc/drbd.conf закомментировать строчку «include »drbd.d/*.res»;».
Очищаем /dev/sdb1 (на двух серверах, процесс долгий, можно не дожиться окончания и прервать минут через 5-10):
$sudo dd if=/dev/zero of=/dev/sdb1
Инициализируем метаданные DRBD (на обоих серверах):
$sudo drbdadm create-md r0
После успешной инициализации, запускаем drbd на обоих нодах:
$sudo service drbd start
Переводим одну из нод (UbuntuServer1) в состояние Primary:
$sudo drbdsetup /dev/drbd0 primary -o
Дождаться окончания синхронизации, отслеживать процесс:
$cat /proc/drbd
После окончания синхронизации на второй ноде выполнить:
$sudo drbdsetup /dev/drbd0 primary -o
Теперь у нас есть два сервера с drbd в режиме primary-primary, что даст нам возможность монтировать устройства на своих серверах локально и не только.
4. Установка и настройка кластерной файловой системы OCFS2
4.1. Установка OCFS2
$sudo apt-get install ocfs2-tools
4.2 Настройка OCFS2
Форматирование устройства /dev/drbd0 в ocfs2 (только на одной из нод):
$sudo mkfs.ocfs2 -b 4K -N 2 -v /dev/drbd0
Далее для того, чтобы было возможно монтирование раздела по ocfs2 нам надо настроить для него кластер o2cb:
Создаём файл конфигурации кластера для OCFS2 (на обоих нодах, файл чувствителен к пробелам и табуляции):
$sudo nano /etc/ocfs2/cluster.conf
 
cluster:
 
node_count = 2
 
name = ocfs2
 
node:
 
ip_port = 7777
 
ip_address = 10.0.3.201
 
number = 0
 
name = UbuntuServer1
 
cluster = ocfs2
 
node:
 
ip_port = 7777
 
ip_address = 10.0.3.205
 
number = 1
 
name = UbuntuServer2
 
cluster = ocfs2
Загружаем модули и запускаем кластер o2cb на обоих нодах:
$sudo /etc/init.d/o2cb load
 
$sudo /etc/init.d/o2cb online
Запустить конфигуратор ocfs2, в котором выбрать «да» при вопросе о запуске ocfs2 при загрузке системы (либо в /etc/default/o2cb в строке O2CB_ENABLE поставить true), остальное оставить как есть.
$sudo dpkg-reconfigure ocfs2-tools
5. Монтирование файловой системы ocfs2 и автомонтирование
Производим монтирование раздела в /home по ocfs2 на обоих нодах:
$sudo mount -t ocfs2 /dev/drbd0 /home
Создадим скрипт на обоих нодах /etc/init.d/mountdrbd для монтирования раздела drbd (fstab в данном случае не подошёл, т. к. монтирует до запуска drbd, тоесть не сможет смонтировать):
$sudo nano /etc/init.d/mountdrbd
 
#!/bin/bash
 
mount -t ocfs2 /dev/drbd0 /etc_drbd
Сделать файл скрипта выполняемым:
$sudo chmod 755 /etc/init.d/mountdrbd
Сделать символические ссылки (на обоих нодах) на /etc/init.d/mountdrbd вида /etc/rc2.d/@S72mountdrbd, /etc/rc3.d/@S72mountdrbd, /etc/rc4.d/@S72mountdrbd, /etc/rc5.d/@S72mountdrbd.
6. Заметки
Если случилась неприятная ситуация, когда основной сервер просто грубо перезагрузили, а на втором – подняли drbd primary. Синхронизация нарушилась, и связка primary/secondary перестала работать. Нужно тот сервер, который упал или который грубо перезагружали насильно синхронизировать (допустим, это UbuntuServer1):
UbuntuServer1:~ # drbdadm -- --discard-my-data connect all
 
UbunruServer2:~ # drbdadm connect all

Static IP and Network Configuration on Debian Linux

This guide explains how to configure static IP address, dns configuration and hostname on debian based Linux distributions on the shell. It will be same on server & desktop.

Preliminary Note

Suppose you are working in a data center or company and your boss puts a dumb debian server setup and you need to configure it in the running environment. Yes it is little painstaking, but not very tough task. In my case I have a dumb debian server which was installed by someone in his networking environment and I want to make it functional in my static IP environment. Suppose I have a vacant IP 192.168.0.100 and I will implement it in my environment. My IP details are as follows:
IPv4
IP 192.168.0.100
subnet 255.255.255.0
gateway 192.168.0.1
IPv6
address 2001:db8::c0ca:1eaf
netmask 64
gateway 2001:db8::1ead:ed:beef
DNS
8.8.8.8
8.8.4.4
All the above values will be fitted as per your environment. It will differ in your case. The DNS Servers 8.8.8.8 and 8.8.4.4 are free public DNS servers from Google, you may use them on your server for free. I will use the editor nano in the examples Use your preferred text editor to edit the configuration files (e.g. nano, vi, joe etc.). If you use "nano" editor, type Ctrl+x to save changes.

Network configuration

I will do manual configuration with root credentials of the network config file, which is the responsible for the IP information in my debian system. The file name is /etc/network/interfaces I will first make backup of my original file as/etc/network/interfaces.bak and then proceed for the changes /etc/network/interfaces
mv /etc/network/interfaces /etc/network/interfaces.bak
nano /etc/network/interfaces
I will change  the value like this
auto lo
iface lo inet loopback


#My IP description
# IPv4 address
iface eth0 inet static
 address 192.168.0.100
 netmask 255.255.255.0 
 network 192.168.0.0 
 broadcast 192.168.0.255
 gateway 192.168.0.1
For IPv-6 You just need to add the entires below the segment as
nano /etc/network/interfaces
[...]
#IPv6 address
iface eth0 inet6 static
        address 2001:db8::c0ca:1eaf
        netmask 64
        gateway 2001:db8::1ead:ed:beef

DNS configuration

DNS can be added in the file /etc/resolv.conf
nano /etc/resolv.conf
nameserver 8.8.8.8 
nameserver 8.8.4.4
Note : DNS entries with the debian system will only works if resolvconf is not installed. If resolvconf is installed then you need to append the DNS entries in the file /etc/network/interfaces only as follows:
[....]

#DNS configurations
dns-nameservers 8.8.8.8
dns-nameservers 8.8.4.4
You can check whether resolvconf is installed or not by
dpkg -l | grep resolvconf
Note: DNS entries can be either enterd in /etc/network/interfaces or /etc/resolv.conf. There shouldn't be double entries.

Set or change the Hostname

In my case the hostname is server1.example.com to add the hostname use:
echo server1.example.com > /etc/hostname
Again add it here in
nano /etc/hosts
[...]
127.0.0.1     localhost
192.168.0.1   server1.example.com server1
[...]
/etc/init.d/hostname.sh start
Check your hostname by using below code Now the value must be same for both cases

Advanced networking
hostname
hostname -f
 I am using Debian Linux and I would like to  create alias for eth0 so that I can have multiple IP address. I will implemented by appending it as follows:
nano /etc/network/interfaces
[....]

#IP Aliasing
auto eth0:0
iface eth0:0 inet static
 name Ethernet alias LAN card
 address 192.168.0.108
 netmask 255.255.255.0
 broadcast 192.168.0.255
 network 192.168.0.0
Note: There will be no extra column for the Gateway.
Here I have done the IP aliasing for the IP 192.168.0.108, it could vary as per your requirement.

Restart Networking Service

After any change in the networking files you need to restart the network services as follows:
service networking restart
On Debian 7, use the following command instead:
/etc/init.d/networking restart

After the service restart you can check the changes as:
ifconfig
The output will confirm the changes done statically. It will be almost similar like this:
root@server1:~# ifconfig
eth0      Link encap:Ethernet  HWaddr 20:89:84:c8:12:8a 
          inet addr:192.168.0.100  Bcast:192.168.0.255  Mask:255.255.255.0
          inet6 addr: fe80::2289:84ff:fec8:128a/64 Scope:Link
          UP BROADCAST RUNNING MULTICAST  MTU:1500  Metric:1
          RX packets:200197 errors:0 dropped:67 overruns:0 frame:0
          TX packets:69689 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:1000
          RX bytes:64103748 (64.1 MB)  TX bytes:14106191 (14.1 MB)
          Interrupt:16 

eth0:0    Link encap:Ethernet  HWaddr 20:89:84:c8:12:8a 
          inet addr:192.168.0.108  Bcast:192.168.0.255  Mask:255.255.255.0
          inet6 addr: fe80::2289:84ff:fec8:128a/64 Scope:Link
          UP BROADCAST RUNNING MULTICAST  MTU:1500  Metric:1
         

How To Create and Install SSH Keys on the Shell


SH keys offer a highly secure manner of logging into a server with SSH as against mere dependence on a password. While a password stands the risk of being finally cracked, SSH keys are rather impossible to decipher using brute force. As a matter of fact, generating a key pair offers users two lengthy strings of characters corresponding to a public as well as a private key. Users can, thus, place the public key on any server, and subsequently unlock the same by connecting to it with a client that already possesses the private key. Upon matching up of the two keys, the system unlocks without any irksome dependence on a password. The security may be further smartly firewalled by guarding the private key with a passphrase.

1.2 Installation of SSH Keys on Linux-A Step-By Step Guide

Outlined below is a step-by-step guide detailing the process of installing SSH Keys on a Linux server:

Step One-Creation of the RSA Key Pair

The first step in the installation process is to create the key pair on the client machine, which would, more often than not, be your own system. Users need to use the following command:
ssh-keygen -t rsa
The above command kicks off the SSH Key installation process for users.

Step Two-Storing the Keys and Passphrasing

Upon entering the primary Gen Key command, users need to go through the following drill by answering the following prompts:
Enter the file where you wish to save the key (/home/demo/.ssh/id_rsa)
Users need to press ENTER in order to save the file to the user home
The next prompt would read as follows:
Enter passphrase
If, as an administrator, you wish to assign the passphrase, you may do so when prompted (as per the question above), though this is optional, and you may leave the field vacant in case you do not wish to assign a passphrase.
However, it is pertinent to note there that keying in a unique passphrase does offer a bevy of benefits listed below:
1. The security of a key, even when highly encrypted, depends largely on its invisibility to any other party. I 2. In the likely instance of a passphrase-secure private key falling into the custody of an unauthorized user, they will be rendered unable to log in to its allied accounts until they can crack the passphrase. This invariably gives the victim (the hacked user) precious extra time to avert the hacking bid On the downside, assigning a passphrase to the key requires you to key it in every time you make use of the Key Pair, which makes the process a tad tedious, nonetheless absolutely failsafe.
Here is a broad outline of the end-to-end key generation process:
root@server1:~# ssh-keygen -t rsa
Generating public/private rsa key pair.
Enter file in which to save the key (/root/.ssh/id_rsa):
Enter passphrase (empty for no passphrase):
Enter same passphrase again:
Your identification has been saved in /root/.ssh/id_rsa.
Your public key has been saved in /root/.ssh/id_rsa.pub.
The key fingerprint is:
38:16:50:fe:8d:da:02:bb:46:1b:66:0c:10:8e:81:2d root@server1.example.com
The key's randomart image is:
+--[ RSA 2048]----+
|+o ... |
|E.. o |
|.+ o |
| . + o |
| o. + S . |
| *+ + |
| +.oo . |
| o. . |
| .. |
+-----------------+
The public key can now be traced to the link ~/.ssh/id_rsa.pub
The private key (identification) can now be traced to the link-/home/demo/.ssh/id_rsa 3

Step Three-Copying the Public Key

Once the distinct key pair has been generated, the next step remains to place the public key on the virtual server that we intend to use. Users would be able to copy the public key into the authorized_keys file of the new machine using the ssh-copy-id command. Given below is the prescribed format (strictly an example) for keying in the username and IP address, and must be replaced with actual system values:
As an alternative, users may paste the keys by using SSH (as per the given command):
cat ~/.ssh/id_rsa.pub | ssh user@192.168.0.100 "cat >> ~/.ssh/authorized_keys"
Either of the above commands, when used, shall toss the following message on your system:
The authenticity of host '192.168.0.100 ' can't be established. RSA key fingerprint is b1:2d:32:67:ce:35:4d:5f:13:a8:cd:c0:c4:48:86:12. Are you sure you want to continue connecting (yes/no)? yes Warning: Permanently added '192.168.0.100' (RSA) to the list of known hosts. user@192.168.0.100's password: Now try logging into the machine, with "ssh 'user@192.168.0.100'", and check in: ~/.ssh/authorized_keys to make sure we haven't added extra keys that you weren't expecting.
After the above drill, users are ready to go ahead and log into user@192.168.0.100 without being prompted for a password. However, if you have earlier assigned a passphrase to the key (as per Step 2 above), you will be prompted to enter the passphrase at this point (and each time for subsequent log-ins.).

Step Four (This Step is Optional)-Disabling the Password to Facilitate Root Login

After users have copied their SSH keys unto your server and ensured seamless log-in with the SSH keys only, they have the option to restrict the root login, and permit the same only through SSH keys. To accomplish this, users need to access the SSH configuration file using the following command:
sudo nano /etc/ssh/sshd_config
Once the file is accessed, users need to find the line within the file that includes PermitRootLogin , and modify the same to ensure a foolproof connection using the SSH key. The following command shall help you do that:
PermitRootLogin without-password
The last step in the process remains to implement the changes by using the following command:
reload ssh
The above completes the process of installing SSH keys on the Linux server.

Conclusion

The above steps shall help you install SSH keys on any virtual private server in a completely safe, secure and hassle-free manner.

Best CPM Ad Networks For Publishers 2019

It is an undeniable fact that the mid-market publishers have always been looking for the ideal CPM ad networks to partner with. You c...