воскресенье, 1 ноября 2009 г.

vsftpd - создание файлопомойки

/*
... есть такое слово - samba...

цели:
* выкинуть "самбу"
* анонимусов в chroot и дать им все возможности для самореализации
* локальных/виртуальных лузеров тоже в chroot по домашним каталогам
* всё файло, что зальют аноны, должно иметь mode 0666
* все новые каталоги - mode 0777 (чтобы не парить мозг с правами/чисткой и одминить удалённо тем же ftp-клиентом)
* админов сервиса - в chroot не ставить (или ставить - на выбор, лучше конечно в chroot)

платформа - OpenBSD (ибо тут есть где развернуться), но должно работать везде. подробности о том, как установить и запустить vsftpd опустим. всем пользователям прочих фтп (особенно proftpd) пожелаем удачных обновлений и не скучать :). поехали...

* создаём chroot для анонимусов:
(Прим.: лучше загнать в ~/tmp/vsftpd/anon, а одминов сервиса - в ~/tmp/vsftpd)

> mkdir -p ~/tmp/vsftpd
> chmod 555 ~/tmp/vsftpd
> sudo echo 'anon_root=!ПОЛНЫЙ_ПУТЬ!/tmp/vsftpd' > /etc/vsftpd.conf
> mkdir -p ~/tmp/vsftpd/pub
> chmod 555 ~/tmp/vsftpd/pub
> mkdir -p ~/tmp/vsftpd/upload
> chmod 777 ~/tmp/vsftpd/upload

* добиваем /etc/vsftpd.conf

# Allow anonymous FTP? (Beware - allowed by default if you comment this out).
#anonymous_enable=NO
anonymous_enable=YES
#
# Uncomment this to allow local users to log in.
local_enable=YES
#
# Uncomment this to enable any form of FTP write command.
write_enable=YES
#
# Default umask for local users is 077. You may wish to change this to 022,
# if your users expect that (022 is used by most other ftpd's)
local_umask=000
anon_umask=000
chown_upload_mode=0666
file_open_mode=0666
#
# Uncomment this to allow the anonymous FTP user to upload files. This only
# has an effect if the above global write enable is activated. Also, you will
# obviously need to create a directory writable by the FTP user.
anon_upload_enable=YES
#
# Uncomment this if you want the anonymous FTP user to be able to create
# new directories.
anon_mkdir_write_enable=YES
anon_other_write_enable=YES

# Activate directory messages - messages given to remote users when they
# go into a certain directory.
dirmessage_enable=YES
#
# Activate logging of uploads/downloads.
xferlog_enable=YES
dual_log_enable=YES
#
# Make sure PORT transfer connections originate from port 20 (ftp-data).
connect_from_port_20=YES
# You may override where the log file goes if you like. The default is shown
# below.
xferlog_file=/var/log/xferlog.log
vsftpd_log_file=/var/log/vsftpd.log
#
# If you want, you can have your log file in standard ftpd xferlog format.
# Note that the default log file location is /var/log/xferlog in this case.
xferlog_std_format=YES
# It is recommended that you define on your system a unique user which the
# ftp server can use as a totally isolated and unprivileged user.
nopriv_user=_vsftpd
ftp_username=anonftp
# You may specify a file of disallowed anonymous e-mail addresses. Apparently
# useful for combatting certain DoS attacks.
deny_email_enable=YES
# (default follows)
banned_email_file=/etc/vsftpd.banned_emails
#
# You may specify an explicit list of local users to chroot() to their home
# directory. If chroot_local_user is YES, then this list becomes a list of
# users to NOT chroot().
chroot_local_user=YES
chroot_list_enable=YES
# (default follows)
chroot_list_file=/etc/ftpchroot
#
# You may activate the "-R" option to the builtin ls. This is disabled by
# default to avoid remote users being able to cause excessive I/O on large
# sites. However, some broken FTP clients such as "ncftp" and "mirror" assume
# the presence of the "-R" option, so there is a strong case for enabling it.
ls_recurse_enable=YES
#
#
# If enabled, vsftpd will load a list of usernames from the filename
# given by userlist_file. If a user tries to log in using a name in this
# file, they will be denied before they are asked for a password.
# This may be useful in preventing clear text passwords being transmitted.
userlist_enable=YES
#
# This option is the name of the file loaded when the userlist_enable
# option is active.
userlist_file=/etc/ftpusers
#
# This option should be the name of a directory which is empty. Also,
# the directory should not be writable by the ftp user. This directory
# is used as a secure chroot() jail at times vsftpd does not require
# filesystem access.
secure_chroot_dir=/var/empty
#
# The minimum port to allocate for PASV style data connections.
# Can be used to specify a narrow port range to assist firewalling.
pasv_min_port=49152
#
# The maximum port to allocate for PASV style data connections.
# Can be used to specify a narrow port range to assist firewalling.
pasv_max_port=65535
#
# By default, numeric IDs are shown in the user and group fields of
# directory listings. You can get textual names by enabling this parameter.
# It is off by default for performance reasons.
text_userdb_names=YES
# When "listen" directive is enabled, vsftpd runs in standalone mode and
# listens on IPv4 sockets. This directive cannot be used in conjunction
# with the listen_ipv6 directive.
listen=YES


imho для новичков есть несколько моментов, заслуживающих внимания:

> sudo touch /etc/vsftpd.banned_emails
(иначе "не пойдёт!")

> sudo useradd -d !ПОЛНЫЙ_ПУТЬ!/tmp/vsftpd -s /sbin/nologin anonftp
(иначе в OpenBSD сервис не стартанёт, ибо ftp_username по-умолчанию не объявлен)

> sudo echo 'ИМЯ_ОДМИНА_СЕРВИСА' >> /etc/ftpchroot
(а все остальные гаврики встанут в chroot в своих домашних каталогах)

в "/etc/ftpusers" у нас список тех, кому доступ на ftp заказан. также у нас УЖЕ есть пользователь "_vsftpd" с шеллом "/sbin/nologin" и несуществующим домашним каталогом (требуется по nopriv_user параметру). ACHTUNG! при подобном раскладе все симлинки, "вылетающие" за chroot, идут лесом (и это правильно. в Linux используем конструкцию "mount --bind -o ro" для наполнения "~/tmp/vsftpd/pub", в OpenBSD аналога "mount --bind" нет, сосём заполняем вручную). в "~/tmp/vsftpd/pub" закидываем контент и пишем "~/tmp/vsftpd/README!" файл с общим набором правил пользования сервисом.

всё, база готова. но решение несколько не кошерно. можно (и нужно) одминов сервиса также загнать в chroot, дав им хомяка в ~/tmp, а лучше - скинув анона в ~/tmp/vsftpd/anon (и хомяк одминам в ~/tmp/vsftpd) - тогда все будут счастливо возиться в песочнице и ваш сон никто не потревожит.

на что можно обратить внимание:

anon_max_rate
The maximum data transfer rate permitted, in bytes
per second, for anonymous clients.
Default: 0 (unlimited)
local_max_rate
The maximum data transfer rate permitted, in bytes
per second, for local authenticated users.
Default: 0 (unlimited)
max_per_ip
If vsftpd is in standalone mode, this is the maxi-
mum number of clients which may be connected from
the same source internet address. A client will get
an error message if they go over this limit.
Default: 0 (unlimited)

очень нравятся настройки ниже - можно спокойно и DSA вломить:

ssl_enable=YES
# Should include both certificate and key
rsa_cert_file=/your/cert/file
force_local_logins_ssl=YES
force_local_data_ssl=YES
force_anon_data_ssl=YES
force_anon_logins_ssl=YES
ssl_ciphers=DES-CBC3-SHA

также для хостеров порно полезен параметр (файлы доступны только если знать их имя, просмотр директории их не отобразит):

hide_file={*.mp3,.hidden,hide*,*.avi}

управление дисковыми квотами оставляем за OCью (эт элементарно).

собсно наше упражнение сукесфули комплитед, все новые каталоги получают mode 777 (непринуждённо удаляются одминами сервиса), новое файло, залитое анонами, mode 666, "самба" RIP.

удачи.

*/

9 комментариев:

TheMixa комментирует...

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

sda комментирует...

у нас уже везде есть аналоги curlftpfs, ftpfs, даже есть sshfs и собсно локальные сетки вполне позволяют не думать о подобных мелочах. windows как-то плохо к nfs-у относится, а вот с ftp вопросов не возникает. в любом случае цели и задачи у всех разные, кто-то несомненно вынужден пользовать samba, но vsftpd на файлопомойку - эт прекрасно. полагаю, что плюсы этого решения всем очевидны.

Fed комментирует...

А что ты имел ввиду, когда написал "можно спокойно и DSA вломить"?

sda комментирует...

только то, что vsftpd спокойно работает с двумя типами ключей при SSL подключении (т.е. идёт шифрование трафика) - это DSA (опции dsa_cert_file и dsa_private_key_file) и RSA (rsa_cert_file, rsa_private_key_file). по-умолчанию валиден RSA, но он уже "не торт".

Fed комментирует...

Конечно это все хорошо, но меня больше интересует можно ли ему сказать чтобы шифрование осуществлялось, хотя бы с помощью 3DES или blowfish? А то старенький DES, вобще не радует.

sda комментирует...

здесь вы ограничены только тем, что поддерживается вашим SSL соединением:

ciphers(1)

по мне так можно поиграть с ccgost SSL engine или пользовать 128-ми битные если паранойя не дремлет :)

Fed комментирует...

Точно, ccgost, былобы вобще замечательно. Осталось понять как все это прикрутить к openssl.

Анонимный комментирует...

Как сделать корень anon_root записываемым для анонимусов?
anon_root/upload не красиво
vsftp не пускает, если сделать chmod 777 ftp_root
но уж очень охота :)

sda комментирует...

anon_root/upload не красиво

а иначе никак imho...