olemskoi.ru

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

Ensuring secure access to Production Linux Servers (перепечатка)

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

I was amazed to hear from my friend that one of their server got hacked and reason may be that their part-time admin set password of root user as ‘admin’. Wow!! can’t believe it! They dont have right to cry about security attacks as they themselves keep their door opens I’ve suggested them some points [...]

SFTP: Chroot в домашнюю папку (перепечатка)

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

В новых версиях openssh (хотя не таких уж и новых, >= 4.9 если не ошибаюсь) есть возможность ограничить доступ пользователя в подсистеме sftp. Т.е. задать ему ChrootDirectory, как в proftpd. Например в домашнюю папку (ибо нефиг лазить за её пределами). Рассмотрим, как это можно реализовать.

Для начала, создадим группу sftpusers. Ограничения будут действовать только на пользователей из этой группы (мы ведь не хотим ограничивать пользователя root?):

addgroup --system sftpusers

Далее заменим подсистему sftp в /etc/ssh/sshd_config:

-Subsystem sftp /usr/lib/openssh/sftp-server
+Subsystem sftp internal-sftp

Ну и наконец запишем ограничения в тот же файл:

Match Group sftpusers
        ChrootDirectory %h
        ForceCommand internal-sftp
        AllowTcpForwarding no

Не забываем перечитать конфиг:

invoke-rc.d ssh reload

Теперь разберемся с пользователями. При создании пользователя не надо указывать ему шелл, так как он все равно не сможет им воспользоваться (см. ForceCommand internal-sftp). Поэтому указываем в качестве шелла /bin/false. Домашняя папка (точнее папка, которую мы указали в ChrootDirectory) обязательно должна иметь владельцем пользователя root. Иначе будем получать ошибку:

fatal: bad ownership or modes for chroot directory "/home/%username%"

А вот группу-владельца chroot-папки можно задать любую. Но главное условие – chroot-директория должна быть доступна на запись только для пользователя root и никого больше. В противном случае получим вышеприведенную ошибку.

Рассмотрим пример создания пользователя:

useradd -G sftpusers -s /bin/false -d /home/user1 user1
mkdir /home/user1
chown root:user1 /home/user1
chmod 750 /home/user1

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

ChrootDirectory /home

А внутри /home разруливать доступ к папкам, используя обычные права доступа.

Как удобно копировать файлы и папки между серверами, соблюдая доступы

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

Это удобнее всего сделать используя tar через ssh:

tar zcvf - /files | ssh root@192.168.0.1 "cat > /files.tar.gz"

03.02.2010

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

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

Теги: , , ,

Crash course in dsh (перепечатка)

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

Thanks to a recommendation from Michael and Florian, I've been using dsh with a lot of success for quite some time. In short, dsh is a small application which will allow you to run commands across many servers via ssh very quickly.

You may be wondering: «Why not just use ssh in a for loop?» Sure, you could do something like this in bash:

for i in`cat ~/myhosts.txt`; do ssh $i 'uptime'; done

But dsh allows you to do this:

dsh -g myhosts 'uptime'

In addition, dsh allows you to run the commands concurrently (-c) or one after the other (-w). You can tell it to prepend each line with the machine's name (-M) or it can omit the machine name from the output (-H). If you need to pass extra options, such as which ssh key to use, or an alternative port, you can do that as well (-o). All of these command line options can be tossed into a configuration file if you have a default set of options you prefer.

Another thing that makes dsh more powerful is the groups feature. Let's say you have three groups of servers — some are in California, others in Texas, and still others in New York. You could make three files for the groups:

  • ~/.dsh/group/california
  • ~/.dsh/group/texas
  • ~/.dsh/group/newyork

Inside each file, you just need to list the hosts one after the other. Here's the ~/.dsh/group/texas group file:

db1.tx.mydomain.com
db2.tx.mydomain.com
web1.tx.mydomain.com
web2.tx.mydomain.com
#web3.tx.mydomain.com

As you can see, dsh handles comments in the hosts file. In the above example, the web3 server will be skipped since it's prepended with a comment. Let's say you want to check the uptime on all of the Texas servers as fast as possible:

dsh -c -g texas 'uptime'

That will run the uptime command on all of the servers in the Texas group concurrently. If you need to run it on two groups at once, just pass another group (eg. -g texas -g california) as an argument. You can also run the commands against all of your groups (-a).

The dsh command can really help you if you need to gather information or run simple commands on many remote servers. If you find yourself using it often for systems management, you may want to consider something like puppet.

©2010 Racker Hacker. All Rights Reserved.

.

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

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

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

Теги: , , , ,