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

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

Kerberos for haters (перепечатка)

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

I'll be the first one to admit that Kerberos drives me a little insane. It's a requirement for two of the exams in Red Hat's RHCA certification track and I've been forced to learn it. It provides some pretty nice security features for large server environments. You get central single sign ons, encrypted authentication, and bidirectional validation. However, getting it configured can be a real pain due to some rather archaic commands and shells.

Here's Kerberos in a nutshell within a two-server environment: One server is a Kerberos key distribution center (KDC) and the other is a Kerberos client. The KDC has the list of users and their passwords. Consider a situation where a user tries to ssh into the Kerberos client:

  • sshd calls to pam to authenticate the user
  • pam calls to the KDC for a ticket granting ticket (TGT) to see if the user can authenticate
  • the KDC replies to the client with a TGT encrypted with the user's password
  • pam (on the client) tries to decrypt the TGT with the password that the user provided via ssh
  • if pam can decrypt the TGT, it knows the user is providing the right password

Now that the client has a a TGT for that user, it can ask for tickets to access other network services. What if the user who just logged in wants to access another Kerberized service in the environment?

  • client calls the KDC and asks for a ticket to grant access to the other service
  • KDC replies with two copies of the ticket:
    • one copy is encrypted with the user's current TGT
    • a second copy is encrypted with the password of the network service the user wants to access
  • the client can decrypt the ticket which was encrypted with the current TGT since it has the TGT already
  • client makes an authenticator by taking the decrypted ticket and encrypting it with a timestamp
  • client passes the authenticator and the second copy of the ticket it received from the KDC
  • the other network service decrypts the second copy of the ticket and verifies the password
  • the other network service uses the decrypted ticket to decrypt the authenticator it received from the client
  • if the timestamp looks good, the other network service allows the user access

Okay, that's confusing. Let's take it one step further. Enabling pre-authentication requires that clients send a request containing a timestamp encrypted with the user's password prior to asking for a TGT. Without this requirement, an attacker can ask for a TGT one time and then brute force the TGT offline. Pre-authentication forces the client to send a timestamped request encrypted with the user's password back to the KDC before they can ask for a KDC. This means the attacker is forced to try different passwords when encrypting the timestamp in the hopes that they'll get a TGT to work with eventually. One would hope that you have something configured on the KDC to set off an alarm for multiple failed pre-authentication attempts.

Oh, but we can totally kick it up another notch. What if an attacker is able to give a bad password to a client but they're also able to impersonate the KDC? They could reply to the TGT request (as the KDC) with a TGT encrypted with whichever password they choose and get access to the client system. Enabling mutual authentication stops this attack since it forces the client to ask the KDC for the client's own host principal password (this password is set when the client is configured to talk to the KDC). The attacker shouldn't have any clue what that password is and the attack will be thwarted.

By this point, you're either saying «Oh man, I don't ever want to do this.» or «How do I set up Kerberos?». Stay tuned if you're in the second group. I'll have a dead simple (or as close to dead simple as one can get with Kerberos) how-to on the blog shortly.

In the meantime, here are a few links for extra Kerberos bedtime reading:

Kerberos for haters is a post from: Major Hayden's Racker Hacker blog.

Thanks for following the blog via the RSS feed. Please don't copy my posts or quote portions of them without attribution.

Receive e-mail reports for SELinux AVC denials (перепечатка)

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

SELinux isn't a technology that's easy to tackle for newcomers. However, there's been a lot of work to smooth out the rough edges while still keeping a tight grip on what applications and users are allowed to do on a Linux system. One of the biggest efforts has been around setroubleshoot.

The purpose behind setroubleshoot is to let users know when access has been denied, help them resolve it if necessary, and to reduce overall frustration while working through tight security restrictions in the default SELinux policies. The GUI frontend for setroubleshoot is great for users who run Linux desktops or those who run servers with a display attached. Don't worry, you can configure setroubleshoot on remote servers to send alerts elsewhere when a GUI alert isn't an option.

Install a few packages to get started:

yum install setroubleshoot{-server,-plugins,-doc}

Open /etc/setroubleshoot/setroubleshoot.conf in your favorite text editor and adjust the [email] section to fit your server:

recipients_filepath = /var/lib/setroubleshoot/email_alert_recipients
smtp_port = 25
smtp_host = localhost
from_address = selinux@myserver.com
subject = [MyServer] SELinux AVC Alert

You could probably see it coming, but you need to put the e-mail addresses for your recipients into /var/lib/setroubleshoot/email_alert_recipients:

echo "selinux@mycompany.com" >> /var/lib/setroubleshoot/email_alert_recipients

You'll notice that setroubleshoot doesn't have an init script and it doesn't exist in systemd in Fedora 15. It runs through the dbus-daemon and a quick bounce of the messagebus via its init script brings in the necessary components to run setroubleshoot:

service messagebus restart

A really easy (and safe) test is to ask sshd to bind to a non-standard port. Simply define an additional port on in your /etc/ssh/sshd_config like this:

Port 22
Port 222

When you restart sshd, it will bind to port 22 with success, but it won't be allowed to bind to port 222 (since that's blocked by SELinux as a non-standard port for the ssh_port_t port type). DON'T WORRY! Your sshd server will still be listening on port 22. If you wait a moment, you'll get an e-mail (perhaps two) that not only notify you of the denial, but they make suggestions for how to fix it:

SELinux is preventing /usr/sbin/sshd from name_bind access on the tcp_socket port 222.
 
*****  Plugin bind_ports (99.5 confidence) suggests  *************************
 
If you want to allow /usr/sbin/sshd to bind to network port 222
Then you need to modify the port type.
Do
# semanage port -a -t PORT_TYPE -p tcp 222
   where PORT_TYPE is one of the following: ...

For this particular example, the quick fix would be to run:

semanage port -a -t ssh_port_t -p tcp 222


Much of this post's information was gathered from the detailed documentation on Fedora's setroubleshoot User's FAQ as well as Dan Walsh's setroubleshoot blog post.

Receive e-mail reports for SELinux AVC denials is a post from: Major Hayden's Racker Hacker blog.

Thanks for following the blog via the RSS feed. Please don't copy my posts or quote portions of them without attribution.

ssh keygen RSA versus DSA (перепечатка)

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

While generating ssh keys, I usually use RSA type since it can be used to generate 2048 bits key, while DSA is restricted to exactly 1024 bits.

ssh-keygen -t rsa -b 2048

read more

Remote backups with tar over ssh (перепечатка)

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

Below is example of backing up users' home directory to remote host piped via ssh:

tar -cvzf - -C /home {username} | ssh {remotehost} 'cat >/path/to/bak/{username}.tgz'

read more

Права на файлы при ssh авторизации по ключу (перепечатка)

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

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

drwx------  5 admin      admin      4096 Nov 30 15:42 admin

Каталог .ssh

drwx------ 2 admin admin 4096 Nov 30 15:23 .ssh

authorized_keys

-rw------- 1 admin admin  213 Nov 30 15:23 authorized_keys

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

Speed up SSH (перепечатка)

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

Try setting up ssh client with compression and use arcfour/blowfish encryption instead. Also avoid ipv6 lookup and reuse connections using
socket:

Add below to ~/.ssh/config

Host *<br /> Ciphers arcfour,blowfish-cbc<br /> Compression yes<br /> AddressFamily inet<br /> ControlMaster auto<br /> ControlPath ~/.ssh/socket-%r@%h:%p

read more

10.09.2010

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 [...]

22.08.2010

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 разруливать доступ к папкам, используя обычные права доступа.

08.03.2010

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

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

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

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

03.02.2010

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

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

Теги: , , ,