Игорь Олемской — практические заметки по системному администрированию Linux CentOS

Архив тега ‘iptables’

Отбиваем DDOS mod_evasive + firewall на CentOS (перепечатка)

Комментариев нет

Анализ DDoS можно производить конечно своими скриптами, парсить логи. Но лучше предоставить это апачевскому mod_evasive.

Ставим mod_evasive, в конфигурации пишем

DOSHashTableSize    3097
DOSPageCount        15
DOSSiteCount        15
DOSPageInterval     3
DOSSiteInterval     3
DOSBlockingPeriod   300
DOSSystemCommand    "/usr/bin/sudo /usr/bin/fwban %s"
  • DOSPageInterval – интервал для хитов определенной страницы
  • DOSSiteInterval – интервал для хитов определенного vhost
  • DOSPageCount – после этого количества хитов по определенному URI в течении интервала DOSPageInterval, айпи будет забанен
  • DOSSiteCount – после этого количества хитов по определенному vhost в течении интервала DOSSiteInterval, айпи будет забанен

Нам понадобиться скрипт для бана на уровне файрвола «/usr/bin/fwban» (вариант для Linux):

#!/bin/bash
if [ "x$1" = "x" ] ; then
    echo "USAGE: $0 IPADDR"
    exit
fi
/sbin/iptables -A BAN -s $1 -j DROP

Ему надо поставить права 755.

Так же нам понадобиться утилита sudo. Она стоит практически везде. В «visudo» закомментируем опцию:

#Defaults    requiretty

И добавим строку

apache  ALL = NOPASSWD: /usr/bin/fwban

где apache – юзер от которого работает апач.

Так же нам понадобиться цепочка BAN в iptables:

iptables -N BAN
iptables -I INPUT -j BAN

Сохраним правила файрвола

/etc/init.d/iptables save

Рестартанем апач. Теперь попробуйте уложить ваш сайт (только не со своего айпи!!!):

ab -n 1000  -c 20 http://yoursite.info/

В логах «жертвы» можно увидеть:

May  6 15:18:25 Server1 mod_evasive[26514]: Blacklisting address 1.2.3.4: possible DoS attack.

А в файрволе:

# iptables-save
---многа букав---
-A BAN -s 1.2.3.4 -j DROP
---многа букав---

Ура! No pasaran.

Да. И конечно, апач лучше бы прикрыть извне nginx’ом.

Да. И данный метод банит айпишнеги перманентно, пока не рестартанет сервер, или не будет сброшена цепочка BAN. Вот такой брутальный метод )

Redirect ports inside OpenVZ containers (перепечатка)

Комментариев нет

For port redirection to work inside OpenVZ containers, ipt_REDIRECT kernel module needs to be loaded in the host. Edit «/etc/sysconfig/vz» and add it to the IPTABLES list.

IPTABLES="ipt_REJECT ipt_tos ipt_TOS ipt_LOG ip_conntrack ip_conntrack_ftp ip_conntrack_irc ipt_owner ipt_length ipt_limit ipt_multiport iptable_filter iptable_mangle ipt_TCPMSS ipt_tcpmss ipt_ttl ipt_length ipt_state iptable_nat ip_nat_ftp ipt_recent ipt_REDIRECT"

This should then allow to redirect ports. So if you need to proxy existing apache via nginx or lighttpd and you do not want to switch apaches' default port 80, then the below rules will do the appropriate redirection to port 81 where nginx/lighttpd server is listening, serving static content and proxying to apache for dynamic content:

# Redirect external web traffic to port 81<br />iptables -t nat -A PREROUTING -s ! 127.0.0.1 -p tcp --dport 80 -j REDIRECT --to-ports 81<br /><br /># Redirect internal port 80 to 81<br />iptables -t nat -A OUTPUT -s 0/0 -d 192.168.10.2 -p tcp --dport 80 -j REDIRECT --to-ports 81

Where 192.168.10.2 is the internal IP resolver of domain/host.

read more

Securing your ssh server (перепечатка)

Комментариев нет

One of the most common questions that I see in href="irc://irc.freenode.net/slicehost">my favorite IRC channel is: «How can I secure sshd on my server?» There's no single right answer, but most systems administrators combine multiple techniques to provide as much security as possible with the least inconvenience to the end user.

Here are my favorite techniques listed from most effective to least effective:

SSH key pairs /> By disabling password-based authentication and requiring ssh key pairs, you reduce the chances of compromise via a brute force attack. This can also help you protect against weak account passwords since a valid private key is required to gain access to the server. However, a weak account password is still a big problem if you allow your users to use sudo.

If you're new to using ssh keys, there are href="http://sial.org/howto/openssh/publickey-auth/">many href="http://www.debian-administration.org/articles/530">great href="http://www.linuxquestions.org/linux/answers/Networking/Public_key_authentication_with_ssh">guides that can walk you through the process.

Firewall /> Limiting the source IP addresses that can access your server on port 22 is simple and effective. However, if you travel on vacation often or your home IP address changes frequently, this may not be a convenient way to limit access. Acquiring a server with trusted access through your firewall would make this method easier to use, but you'd need to href="http://en.wikipedia.org/wiki/Recursion">consider the security of that server as well.

The iptables rules would look something like this:

class="wp_syntax"> class="code">
iptables -A INPUT -j ACCEPT -p tcp --dport 22 -s 10.0.0.20
iptables -A INPUT -j ACCEPT -p tcp --dport 22 -s 10.0.0.25
iptables -A INPUT -j DROP -p tcp --dport 22

Use a non-standard port /> I'm not a big fan of href="http://en.wikipedia.org/wiki/Security_through_obscurity">security through obscurity and it doesn't work well for ssh. If someone is simply scanning a subnet to find ssh daemons, you might not be seen the first time. However, if someone is targeting you specifically, changing the ssh port doesn't help at all. They'll find your ssh banner quickly and begin their attack.

If you prefer this method, simply adjust the Port configuration parameter in your sshd_config file.

Limit users and groups /> If you have only certain users and groups who need ssh access to your server, setting user or group limits can help increase security. Consider a server which needs ssh access for developers and a manager. Adding this to to your sshd_config would allow only those users and groups to access your ssh daemon:

class="wp_syntax"> class="code">
AllowGroups developers
AllowUsers jsmith pjohnson asamuels

Keep in mind that any users or groups not included in the sshd_config won't be able to access your ssh server.

TCP wrappers /> While href="http://en.wikipedia.org/wiki/TCP_Wrapper">TCP wrappers are tried and true, I consider them to be a bit old-fashioned. I've found that many new systems administrators may not think of TCP wrappers when they diagnose server issues and this could possibly cause delays when adjustments need to be made later.

If you're ready to use TCP wrappers to limit ssh connections, check out href="http://docs.redhat.com/docs/en-US/Red_Hat_Enterprise_Linux/5/html/Deployment_Guide/s1-tcpwrappers-access.html">Red Hat's extensive documentation.

fail2ban and denyhosts /> For those systems administrators who want to take a bit more active stance on blocking brute force attacks, there's always href="http://en.wikipedia.org/wiki/Fail2ban">fail2ban or href="http://en.wikipedia.org/wiki/DenyHosts">denyhosts. Both fail2ban and denyhosts monitor your authentication logs for repeated failures, but denyhosts can only work with your ssh daemon. You can use fail2ban with other applications like web servers and FTP servers.

The only downside of using these applications is that if a valid user accidentally tries to authenticate unsuccessfully multiple times, they may be locked out for a period of time. This could be a big problem if you're in the middle of a server emergency.

A quick search on Google will give you instructions on href="http://www.fail2ban.org/wiki/index.php/HOWTOs">fail2ban configuration as well as href="http://denyhosts.sourceforge.net/faq.html#2_0">denyhosts configuration.

Port knocking /> Although href="http://en.wikipedia.org/wiki/Port_knocking">port knocking is another tried and true method to prevent unauthorized access, it can be annoying to use unless you have users who are willing to jump through additional hoops. Port knocking involves a «knock» on an arbitrary port that then allows the ssh daemon to be exposed to the user who sent the original knock.

href="http://www.linuxjournal.com/article/6811">Linux Journal has a great article explaining how port knocking works and it provides some sample configurations as well.

Conclusion /> The best way to secure your ssh daemon is to apply more than one of these methods to your servers. Weighing security versus convenience of access isn't an easy task and it will be different for every environment. Regardless of the method or methods you choose, ensure that the rest of your team is comfortable with the changes and capable of adapting to them efficiently.

href="http://rackerhacker.com/2010/10/12/securing-your-ssh-server/">Securing your ssh server is a post from: Major Hayden's href="http://rackerhacker.com">Racker Hacker blog. style="display: none; visibility: hidden;">c0b6ad7e-f251-11df-b20b-4040336e00ef

13.10.2010

Рубрики: Интересные RSS-выборки (новости)

Теги: , , , , , , , , ,

Оригинал: http://rackerhacker.com/2010/10/12/securing-your-ssh-server/

Источник: Racker Hacker

A simple guide to redundant cloud hosting (перепечатка)

Комментариев нет

Today, on my 28th birthday, I'm finally delivering on a promise to my readers which I made about two months ago. I've written a guide on how to host a web application redundantly in a cloud environment. While it's still a bit of a rough draft, it should be a good starting point for those who haven't worked in virtualized environments before. Also, it may show some of the more experienced systems administrators a new way to do things.

The guide: Redundant Cloud Hosting Guide

As always, if you find anything in the guide that needs improvement, I'm all ears. :-)

A simple guide to redundant cloud hosting is a post from: Major Hayden's Racker Hacker blog.

c0b6ad7e-f251-11df-b20b-4040336e00ef

18.08.2010

Еще один способ отбиться от небольшого DDOS (перепечатка)

Комментариев нет

Все нижеописанное относится к GNU/Linux 2.6.x. ДДОС совершенно тупой, разномастный: syn/tcp/udp/icmp flood тупо на все открытые порты, мегабит на 60. UDP срали вообще куда попало. Но основная атака конечно на HTTP. По этому, тушим сервисы и пишем….

Немного sysctl…

vm.min_free_kbytes=70000
net.core.somaxconn=65536
net.ipv4.tcp_tw_reuse=1
net.ipv4.tcp_tw_recycle=1
net.ipv4.ip_local_port_range = 2000 61000
net.ipv4.tcp_fin_timeout = 25
net.ipv4.tcp_keepalive_time = 600
net.ipv4.tcp_window_scaling = 0
net.ipv4.tcp_timestamps = 0
net.core.rmem_max=16777216
net.core.wmem_max=32777216
net.ipv4.tcp_no_metrics_save=0
net.ipv4.tcp_rmem = 4096 87380 16777216
net.ipv4.tcp_wmem = 4096 187380 32777216
net.core.netdev_max_backlog=16384
net.ipv4.tcp_max_syn_backlog=4096
net.ipv4.ip_conntrack_max=600000
net.ipv4.icmp_echo_ignore_all=1
net.ipv4.netfilter.ip_conntrack_max=500000
net.netfilter.nf_conntrack_max=500000
Не забываем перезапустить Network.

Немного iptables….

# Форвард нам нэ нада
iptables -P FORWARD DROP
# BAN – цепочка для помещения туда айпи хостов, ведущих себя не правильно ) Ну типа
# iptables – I BAN -s 123.123.123.123 -j DROP
iptables -N BAN
# TRUSTED – цепочка для помещения туда правильных хостов и хостов откуда мы сидим в шелле. Типа
# iptables -I TRUSTED -s 111.111.111.111 -j ACCEPT
iptables -N TRUSTED
# Стандартный заголовок, eth1 – наш интерфейс внешний
# если есть еще интерфейсы, надо их тоже запрячь правилами разрешения как у lo
iptables -A INPUT -i lo -j ACCEPT
iptables -A INPUT -i eth1 -m state –state ESTABLISHED -j ACCEPT
iptables -A INPUT -i eth1 -m state –state RELATED -j ACCEPT
# Проход по белым и черным цепочкам
iptables -A INPUT -i eth1 -j TRUSTED
iptables -A INPUT -i eth1 -j BAN
# У меня висит только сервис http, по этому здесь такая себе мини защита по данному порту
# Насчет –seconds 10 –hitcount 10, курим маны, экспериментируем, ставим то, что подойдет.
# Режем всех TCP на порту 80, которые за последние 10 секунд сделали 10 попыток открыть соединение
# (кому то может не подойти!)
iptables -A INPUT -p tcp -m tcp –dport 80 -m state –state NEW -m recent –update –seconds 10 –hitcount 10 –name httpd –rsource -j DROP
# А остальных разрешаем
iptables -A INPUT -i eth1 -p tcp -m tcp –dport 80 -j ACCEPT
# Вот по этой теме ддосеры тоже затрахали, по этому был категоричен
iptables -A OUTPUT -p udp -j DROP
iptables -A OUTPUT -p icmp -j DROP
# Здесь добавить разрешения на прочие порты, у меня прочих не было
# …
# Здесь добавить (!!!) свои айпи, с которых сидишь в шелле
iptables -A TRUSTED -s 111.111.111.111 -j ACCEPT
# Хорошо подумаем, покурим, затаим дыхание и напишем….
iptables -P INPUT DROP
# Что означает зарезать все, что не разрешили на INPUT’е
А теперь запускаем nginx/httpd и прочую лабуду. Надеюсь заработает. У меня заработало, как будто ничего и не происходило :)

11.08.2010

Adding comments to iptables rules (перепечатка)

Комментариев нет

After I wrote a recent post on best practices for iptables, I noticed that I forgot to mention comments for iptables rules. They can be extremely handy if you have some obscure rules for odd situations.

To make an iptables rule with a comment, simply add on the following arguments to the rule:

-m comment --comment "limit ssh access"

Depending on your distribution, you may need to load the ipt_comment or xt_comment modules into your running kernel first.

A full iptables rule to limit ssh access would look something like this:

iptables -A INPUT -j DROP -p tcp --dport 22 -m comment --comment "limit ssh access"

Adding comments to iptables rules is a post from: Major Hayden's Racker Hacker blog.

c0b6ad7e-f251-11df-b20b-4040336e00ef

26.07.2010

Private network interfaces: the forgotten security hole (перепечатка)

Комментариев нет

Regardless of the type of hosting you're using — dedicated or cloud — it's important to take network interface security seriously. Most often, threats from the internet are the only ones mentioned. However, if you share a private network with other customers, you have just as much risk on that interface.

Many cloud providers allow you access to a private network environment where you can exchange data with other instances or other services offered by the provider. The convenience of this access comes with a price: other instances can access your instance on the private network just as easily as they could on the public interface.

Here are some security tips for your private interfaces:

Disable the private interface
This one is pretty simple. If you have only one instance or server, and you don't need to communicate privately with any other instances, just disable the interface. Remember to configure your networking scripts to leave the interface disabled after reboots.

Use packet filtering
The actual mechanism will vary based on your operating system, but filtering packets is the one of the simplest ways to secure your private interface. You can take some different approaches with them, but I find the easiest method is to allow access from your other instances and reject all other traffic.

For additional security, you can limit access based on ports as well as source IP addresses. This could prevent an attacker from having easy access to your other instances if they're able to break into one of them.

Configure your daemons to listen on the appropriate interfaces
If there are services that don't need to be listening on the private network, don't allow them to listen on your private interface. For example, MySQL might need to listen on the private interface so the web server can talk to it, but apache won't need to listen on the private interface. This reduces the profile of your instance on the private network and makes it a less likely target for attack.

Use hosts.allow and hosts.deny
Many new systems administrators forget about how handy tcpwrappers can be for limiting access. If your firewall is down in error, host.allow and hosts.deny could be an extra layer of protection. It's important to ensure that the daemons you are attempting to control are build with tcpwrappers support. Daemons like sshd support it, but apache and MySQL do not.

Encrypt all traffic on the private network
Just because it's called a «private» network doesn't mean that your traffic can traverse the network privately. You should always err on the side of caution and encrypt all traffic traversing the private network. You can use ssh tunnels, stunnel, or the built-in SSL features found in most daemons.

This also brings up an important point: you should know how your provider's private network works. Are there safeguards to prevent sniffing? Could someone else possibly ARP spoof your instance's private IP addresses? Is your private network's subnet shared among many customers?

With all of that said, it's also very important to have proper change control policies so that administrators working after you are fully aware of the security measures in place and why they are important. This will ensure that all of the administrators on your instances will understand the security of the system and they should be able to make sensible adjustments later for future functionality.

©2010 Racker Hacker. All Rights Reserved.

.

02.03.2010

CentOS + OpenVZ: iptables ssh-anti-bruteforce в контейнере

Комментариев нет

Для того, чтобы в контейнере OpenVZ под CentOS заработала блокировка iptables вида (разрешается не больше 4 соединений для порта 22 в течение 180 секунд):

-A INPUT -p tcp -m tcp --dport 22 -m state --state NEW -m recent --update --seconds 180 --hitcount 4 --name DEFAULT --rsource -j DROP
-A INPUT -p tcp -m tcp --dport 22 -m state --state NEW -m recent --set --name DEFAULT --rsource

Необходимо в файле /etc/vz/vz.conf разрешить следующие iptables-модули:

IPTABLES="iptable_filter ipt_multiport ip_conntrack ipt_REJECT"

По-умолчанию ip_conntrack отсутствует в этом списке, iptables при добавлении приведенных выше правил не ругается, но и ничего не работает. :-)

03.12.2009

Написал Игорь Олемской

Рубрики: Мои записи

Теги: , , , ,

debian: добавляем в iptables поддержку ip sets (ipset) (перепечатка)

Комментариев нет

IP Sets – расширение пакетного фильтра ядра iptables, которое позволяет комфортно работать с большими наборами адресов/сетей. При написании правил iptables при этом мы оперируем именованными списками.

Это, пожалуй, единственный на сегодняшний день доступный способ писать правила для большого количества хостов/сетей, не перечисляя каждый из них в отдельном правиле. Если ваш сайт, работающий под linux, подвергается DDOS, вы наверняка уже знаете про IP Sets. Если нет — http://ipset.netfilter.org/.

Утилита ipset живет в одноименном пакете, а все необходимые патчи ядра входят в состав пакета netfilter-extensions-source, который собирается и устанавливается при помощи утилиты module-assistant (которая для удобства имеет более короткое имя: m-a).

Примерный сценарий установки ip sets выглядит так:

$ sudo apt-get install ipset
$ sudo apt-get install netfilter-extensions-source
$ uname -a
Linux host.domain.tld 2.6.26-1-686 #1 SMP Fri Mar 13 18:08:45 UTC 2009 i686 GNU/Linux
# версия пакета linux-headers должна совпадать с версией ядра, для которого собирается netfilter-extensions
$ sudo apt-get install linux-headers-2.6.26-1-686
$ sudo m-a build netfilter-extensions
$ sudo m-a update && m-a a-i netfilter-extensions

Версия пакета заголовков ядра должна точно соответствовать версии активного ядра, для которого собирается ipset.

27.10.2009