Borgia
Full Member | Редактировать | Профиль | Сообщение | Цитировать | Сообщить модератору Организация Небольшой сети на linux Fedore Core3 Часть седьмая конфигурирование FTP server (vsftpd) Ну вот мы наконец добрались до FTP . Вобщем здесь нужно определяться , что нужно для нашей сети всем сделать анонимный доступ всем вход через username, password часть юзеров username, password, часть юзеров анонимный доступ Вот и задумался над одним вариантом , а как например сделать так аннонимный доступ открыть только внутри чтоб снаружи нельзя было зайти . Снаружи только через username ,password. Может есть у кого идеи как организовать это в VSFTPD ? Вот совет от Dr_Spectre повесить два разных сервера с разными конфигами на разные ip 1 директива listen_address в конфигах 2 копируем /etc/rc.d/init.d/vsftpd в /etc/rc.d/init.d/vsftpd_local например 3 правим в файле /etc/rc.d/init.d/vsftpd_local пут к конфигу 4 chkconfig vsftpd_local on 5 service vsftpd_local start Я решил немножко изменить решение и организовать это через ,,супер сервер ,, XINETD . Вначале немного пояснение. Для управления доступом к службам Интернет используется демон xinetd, который является безопасной заменой для inetd. Демон xinetd экономит системные ресурсы, обеспечивает управление доступом и протоколирование, а также может использоваться для запуска серверов специального назначения. xinetd можно использовать для предоставления доступа или запрета доступа только определённым узлам, для предоставления доступа к службе в определённое время, для ограничения количества входящих подключений и/или нагрузки, создаваемой подключениями и т.д. xinetd работает постоянно и прослушивает все порты служб, которыми он управляет. Когда управляемая служба получает запрос на установление соединения, xinetd запускает соответствующий сервер этой службы. Файлом настройки демона xinetd является /etc/xinetd.conf . И так, прослушиванием - кто с какого сетевого интерфеиса, с какой подсети с какого IP adress подключается (можно также установить разрешение по времени ) мы возложим на демон xinetd. Теперь пока оставим xinetd и передем к самому фтп серверу vsftpd . vsftpd используется на большинстве серверов под управлением linux. Среди них ftp.redhat.com, ftp.suse.com, ftp.debian.org, ftp.gnu.org, ftp.gnome.org, ftp.kde.org Название vsftpd произошло от "very secure FTP deamon" (чрезвычайно безопасный FTP-демон) . И так фаил конфигурации находится /etc/vsftpd/vsftpd.conf ( команды для работы с сервисом vsftpd ) # service vsftpd start # service vsftpd stop # service vsftpd restart Проверка работает ли сервис фтп # netstat -a | grep ftp Он изначально уже так настроен что что запустив фтп сервер он работает и с локальными юзерами и как анонимный. Вот линки на другие сайты где расписан файл настройки сервера на руском языке. http://www.linuxcenter.ru/lib/articles/soft/vsftpd_setup.phtml http://linuxshop.ru/linuxbegin/article678.html http://www.tldp.org/linuxfocus/Russian/July2004/article341.shtml Нам же нужно создать два фаила настройки, так как юзер который заходит на фтп снаружи должен заити с username, password, а юзер изнутри сети может и как с username, password так и как аннонимный. То есть один фаила настройки для юзеров снаружи , а другой для внутренних. И так копируем cp /etc/vsftpd/vsftpd.conf /etc/vsftpd/vsftpd_pub.conf vsftpd.conf для внутренних vsftpd_pub.conf для внешних дальше в vsftpd.conf и в vsftpd_pub.conf мы должны закоментировать опцию # listen=YES эта опция для запуска сервера STANDALONE - вручную если сервер будет работать через xinetd то ее нужно закоментировать иначе будем получать ошибку could not bind listening IPv4 socket На этом с vsftpd.conf пока все, а в vsftpd_pub.conf нам нужно запретить фход как анонимный пользователь . вот конфиг. ******************************************************* # Example config file /etc/vsftpd/vsftpd.conf # # The default compiled in settings are fairly paranoid. This sample file # loosens things up a bit, to make the ftp daemon more usable. # Please see vsftpd.conf.5 for all compiled in defaults. # # READ THIS: This example file is NOT an exhaustive list of vsftpd options. # Please read the vsftpd.conf.5 manual page to get a full idea of vsftpd's # capabilities. # # Allow anonymous FTP? (Beware - allowed by default if you comment this out). # 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=022 # # 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 # # 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 # # Make sure PORT transfer connections originate from port 20 (ftp-data). connect_from_port_20=YES # # If you want, you can arrange for uploaded anonymous files to be owned by # a different user. Note! Using "root" for uploaded files is not # recommended! #chown_uploads=YES #chown_username=whoever # # You may override where the log file goes if you like. The default is shown # below. #xferlog_file=/var/log/vsftpd.log # # If you want, you can have your log file in standard ftpd xferlog format xferlog_std_format=YES # # You may change the default value for timing out an idle session. idle_session_timeout=600 # # You may change the default value for timing out a data connection. data_connection_timeout=120 # # 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=ftpsecure # # Enable this and the server will recognise asynchronous ABOR requests. Not # recommended for security (the code is non-trivial). Not enabling it, # however, may confuse older FTP clients. #async_abor_enable=YES # # By default the server will pretend to allow ASCII mode but in fact ignore # the request. Turn on the below options to have the server actually do ASCII # mangling on files when in ASCII mode. # Beware that turning on ascii_download_enable enables malicious remote parties # to consume your I/O resources, by issuing the command "SIZE /big/file" in # ASCII mode. # These ASCII options are split into upload and download because you may wish # to enable ASCII uploads (to prevent uploaded scripts etc. from breaking), # without the DoS risk of SIZE and ASCII downloads. ASCII mangling should be # on the client anyway.. #ascii_upload_enable=YES #ascii_download_enable=YES # # You may fully customise the login banner string: ftpd_banner=Welcome to Microsoft FTP service. # # 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_list_enable=YES # (default follows) #chroot_list_file=/etc/vsftpd.chroot_list # # 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 pam_service_name=vsftpd userlist_enable=YES #enable for standalone mode # listen=no tcp_wrappers=YES ********************************************************** Хочу обратить ваше внимание на следующую опцию # 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_list_enable=YES # (default follows) #chroot_list_file=/etc/vsftpd.chroot_list Я оставил ее без изменения но с точки зрения безопасности вам стоит ее разрешить а в фаил vsftpd.chroot_list впишите например своего юзера . ( кстати фаил vsftpd.chroot_list надо создать самому странно что и самой опции chroot_local_user=YES в конфиге нет) Все с конфигурацией vsftpd закончено , возвращаемся к xinetd. Идем в /etc/xinetd.conf и добавляем следущее вот xinetd.conf ********************************************************* # # Simple configuration file for xinetd # # Some defaults, and include /etc/xinetd.d/ defaults { instances = 60 log_type = SYSLOG authpriv log_on_success= HOST PID log_on_failure= HOST cps= 25 30 } includedir /etc/xinetd.d service ftp { id = ftp-public socket_type = stream wait = no disable = no user = root server = /usr/sbin/vsftpd server_args = /etc/vsftpd/vsftpd_pub.conf instances = 4 #Defines the maximum number of servers of a same type able to work at the same time nice = 10 flags = IPv4 only_from = 0.0.0.0/0 #allows every client interface = 192.168.1.240 #public IP address for this server } service ftp { id = ftp-internal socket_type = stream wait = no disable = no user = root server = /usr/sbin/vsftpd server_args = /etc/vsftpd/vsftpd.conf flags = IPv4 only_from = 192.168.20.0/24 #only for internal use only_from = 192.168.30.0/24 #only for internal use } ********************************************************************* Вот линки по файлу настроек xinetd http://lantan.chat.ru/xinetd.conf.html http://www.tldp.org/linuxfocus/English/November2000/article175.shtml Теперь сама работа с xinetd # service xinetd start # service xinetd stop # service xinetd restart Теперь перезапускаем xinetd и проверяем как это все работает. У меня все работает отлично. Теперь немного о проблемах . Как вы обратили внимание в настройке первого ,, public ,, ftp есть внизу строка interface = 192.168.1.240 #public IP address for this server Этим параметром мы задаем xinetd прослушивать сетевую карточку с конкретным адресом, но IP -то у нас не постоянный - адрес мы получаем от DHCP. И к сожалению xinetd не поддерживает динамик IP. В принципе все не так страшно , всетаки это сервер и притом gateway, и он не перезагружается каждый день и IP у нас не будет менятся часто , здесь главное не забыть что после перезагрузки надо проверить не изменился ли адрес и если что не забыть поменять его в конфиге. Решения проблемы вроде как есть но у меня оно не работает. Вот что я нашел ,, Obviously, there's a problem: what happens if a machine doesn't have two static IP addresses? This can happen with ppp connections or when using the dhcp protocol. It seems it would be much better to bind services to interfaces than to addresses. However, this is not yet supported in xinetd and is a real problem (for instance, writing a C module to access an interface or address depends on the OS, and since xinetd is supported on many OSes...). Using a script solves the problem: #!/bin/sh PUBLIC_ADDRESS=`/sbin/ifconfig $1 | grep "inet addr" | awk '{print $2}'| awk -F: '{print $2}'` sed s/PUBLIC_ADDRESS/"$PUBLIC_ADDRESS"/g /etc/xinetd.base > /etc/xinetd.conf This script takes the /etc/xinetd.base file, containing the desired configuration with PUBLIC_ADDRESS as a replacement for the dynamic address, and changes it in /etc/xinetd.conf, modifying the PUBLIC_ADDRESS string with the address associated to the interface passed as an argument to the script. Next, the call to this script depends on the type of connection: the simplest is to add the call into the right ifup-* file and to restart xinetd. У меня к сожалению этот скрипт чистит весь конфиг фаил , в програмирование я полный дундук поэтому не знаю что здесь можно поменять . Ну и ко всему прочему, почему бы уж тогда нельзя было сделать скрипт более толковый , который после рестарта системы проверяет IP , меняет конфиг , и перестартовывает xinetd. Так что если у кого есть идеи пишите. На этом по ФТП пока все, если есть мысли , дополнения, вопросы пищите. | Всего записей: 545 | Зарегистр. 25-08-2001 | Отправлено: 23:41 21-12-2004 | Исправлено: Borgia, 22:24 22-12-2004 |
|