| При копировании материала обязательны указание автора, переводчика и ссылки на оригинал статьи и страницу первоисточника перевода! Этот документ описывает настройку chroot-окружения для SSH/SFTP на Статья представляет собой практическое описание и не затрагивает Хочу оговориться, что данный способ далеко не единственный, и Метод 1 - ручная настройка Для начала установим некоторые необходимые пакеты yum install openssl-devel pam-devel и поправим конфигурационные файлы. В /etc/ssh/sshd_config GSSAPIAuthentication yes а в /etc/ssh/ssh_config закомментируйте строку GSSAPIAuthentication yes Затем мы скачаем патчи к OpenSSH и сконфигурируем их для наших целей cd /tmp/ Создание chroot-окружения Теперь создадим chroot-окружение в /home/chroot - здесь будут mkdir -p /home/chroot/home/ Теперь, когда необходимые директории созданы, скопируем некоторые #!/bin/bash PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin for prog in $APPS; do mkdir -p ./`dirname $prog` > /dev/null 2>&1 # obtain a list of related libraries for l in $LIBS; do fi Примечание: Вы можете разрешить chroot-пользователям доступ к бОльшему Разместим наш сценарий в /usr/local/sbin, назовем его chmod 700 /usr/local/sbin/create_chroot_env Скопируем еще несколько дополнительных библиотек в наше cp /lib/libnss_compat.so.2 /lib/libcom_err.so.2 /lib/libnsl.so.1 /lib/libnss_files.so.2 /lib/ld-linux.so.2 /lib/libcap.so.1 /lib/libnss_dns.so.2 lib/ Далее выполните следующее: echo '#!/bin/bash' > usr/bin/groups Также мы должны выбрать группу для пользователей chroot и поместить ее grep /etc/group -e "^root" -e "^users" > etc/group Теперь перезапустим SSH-сервер: /etc/init.d/sshd restart Создание пользователей chroot Мы установили chroot-окружение для OpenSSH, но необходимо разделить Пользователь работает в ограниченном окружении: user_b:x:2003:100:User B:/home/chroot/./home/user_b:/bin/bash Пользователь имеет полный доступ: user_a:x:2002:100:User A:/home/user_a:/bin/bash Создадим пользователя testuser с домашней директорией useradd -s /bin/bash -m -d /home/chroot/./home/testuser/ -c "testuser" -g users testuser После создания нового аккаунта необходимо задать пароль для него passwd testuser Теперь скопируем запись для нового пользователя из /etc/passwd в grep /etc/passwd -e "^testuser" >> /home/chroot/etc/passwd Так как мы уже скопировали группу для chroot-пользователей из grep /etc/group -e "^othergroup" >> /home/chroot/etc/group Все готово. Попытайтесь авторизоваться в системе через SSH или SFTP как Метод 2 - использование сценария Существует сценарий, который называется make_chroot_jail.sh. Он yum install sudo Скачаем сценарий и сделаем его исполняемым cd /usr/local/sbin Теперь вы можете создавать chroot-пользователей при помощи следующей make_chroot_jail.sh %username% [%path_to_chrootshell% [%path_to_chroot%]] Например make_chroot_jail.sh testuser /bin/chroot-shell /home/chroot Если пользователь не существует - он будет создан. Если существует, то Для обновления файлов и библиотек в chroot-окружении используйте make_chroot_jail.sh update [%path_to_chrootshell% [%path_to_chroot%]] Например make_chroot_jail.sh update /bin/chroot-shell /home/chroot Параметры %path_to_chrootshell% и %path_to_chroot% не являются Пользователям proFTPd Замечание для пользователей proFTPd: при использовании сценария Проблема решается добавлением в конфигурационный файл RequireValidShell off После внесения изменения перезапустите proFTPd /etc/init.d/proftpd restart Теперь все пользователи, вне зависимости от используемой оболочки, Скрипт make_chroot_jail.sh #!/bin/sh # first Release: 2004-07-30 # # path to sshd's config file: needed for automatic detection of the locaten of # Check if we are called with username or update if [ -z "$PATH" ] ; then echo echo "Am I root? " Error: You must be root to run this script." # Check existence of necessary files # Specify the apps you want to copy to the jail # Check existence of necessary files Please install which-binary! echo "Checking for chroot..." chroot not found! echo "Checking for sudo..." sudo not found! echo "Checking for dirname..." dirname not found! echo "Checking for awk..." awk not found! # get location of sftp-server binary from /etc/ssh/sshd_config #if !(grep -v "^#" /etc/ssh/sshd_config | grep -i sftp-server /etc/ssh/sshd_config | awk '{ print $3}' &> /dev/null); then # Get accountname to create / move if ! [ -z "$2" ] ; then if ! [ -z "$3" ] ; then # Exit if user already exists # Check if user already exists and ask for confirmation Are you sure you want to modify the users home directory and lock him into the # Create $SHELL (shell for jailed accounts) Are you sure you want to overwrite it? # make common jail for everybody if inexistent # Create directories in jail that do not exist yet # Comment in the following lines if your apache can't read the directories and # Creating necessary devices # if we only want to update the files in the jail # Modifiy /etc/sudoers to enable chroot-ing for users # Define HomeDir for simple referencing # Create new account, setting $SHELL to the above created script and if [ "$CREATEUSER" = "yes" ] ; then { # Enter password for new account # Create /usr/bin/groups in the jail # Add users to etc/passwd # grep the username which was given to us from /etc/passwd and add it # if the system uses one account/one group we write the # write the user's line from /etc/shadow to /home/jail/etc/shadow # endif for =! update # Copy the apps and the related libs # The original code worked fine on RedHat 7.3, but did not on FC3. # create temporary files with mktemp, if that doesn't work for some reason use for app in $APPS; do # If the files in the chroot are on the same file system as the # get list of necessary libraries # Clear out any old temporary file before we start # If the files in the chroot are on the same file system as the original # # Necessary files that are not listed by ldd. # if you are using a 64 bit system and have strange problems with login comment # if you are using PAM you need stuff from /etc/pam.d/ in the jail, # ...and of course the PAM-modules... # ...and something else useful for PAM if [ -f /etc/DIR_COLORS ] ; then # Don't give more permissions than necessary exit | |
| Категория: Интересные статьи | Просмотров: 534 | |
Главная » Запуск ssh/sftp в chroot-окружении на Fedora 7