Linux за българи: Форуми

Linux секция за напреднали => Хардуерни и софтуерни проблеми => Темата е започната от: Pulear в Feb 27, 2006, 21:22



Титла: user в chroot jail
Публикувано от: Pulear в Feb 27, 2006, 21:22
здравейте.
Проблема е следния искам да сложа личния си потребител,просто за да знам как става, в chroot jail.
Целта ми е потребителя да може да си ползва основните програми които са му нужни, но да не може да напуска home директорията си за целта ползвам ето този скрипт.
Примерен код

#!/bin/sh
#
# (c) Copyright by Wolfgang Fuschlberger
#
#    This program is free software; you can redistribute it and/or modify
#    it under the terms of the GNU General Public License as published by
#    the Free Software Foundation; either version 2 of the License, or
#    (at your option) any later version.
#
#    This program is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.
#    ( http://www.fsf.org/licenses/gpl.txt )

# first Release: 2004-07-30
# latest update: 2006-02-19
#
# The latest version of the script is available at
#   http://www.fuschlberger.net/programs/ssh-scp-chroot-jail/
#
# Feedback is welcome!
#
# Thanks for Bugfixes / Enhancements to
# Michael Prokop <http://www.michael-prokop.at/chroot/>,
# Randy K., Randy D. and Jonathan Hunter.

#
# Features:
# - enable scp and sftp in the chroot-jail
# - use one directory (default /home/jail/) as chroot for all users
################################################################################

# Specify the apps you want to copy to the jail
APPS="/bin/bash /bin/cp /usr/bin/dircolors /bin/ls /bin/mkdir /bin/mv /bin/rm /bin/rmdir /bin/sh /bin/su /usr/bin/groups /usr/bin/id /usr/bin/rsync /usr/bin/ssh /usr/bin/scp /sbin/unix_chkpwd /usr/libexec/openssh/sftp-server "

# Check if we are called with username or update
if [ -z "$1" ]; then
  echo
  echo "Error: Parameter missing"
  echo
  echo "Creating new chrooted account:"
  echo "Usage: $0 username"
  echo
  echo "or specify \$SHELL and path where the jail should be located:"
  echo "Usage: $0 username [/path/to/chroot-shell [/path/to/jail]]"
  echo "Default shell       = /bin/chroot-shell"
  echo "Default chroot-path = /home/jail"
  echo
  echo "Updating files in the chroot-jail:"
  echo "Usage: $0 update [/path/to/chroot-shell [/path/to/jail]]"
  echo
  echo "To uninstall: # userdel \$USER"
  echo "              # rm -rf /home/jail"
  echo "              # rm -f /bin/chroot-shell"
  echo "              delete the User's line from /etc/sudoers"
  exit
fi

# Check existence of necessary files
echo -n "Checking for chroot... "
if [ `which chroot` ];
  then echo "OK";
  else echo "failed
Please install chroot-package/binary!
"
exit 1
fi

echo -n "Checking for sudo..... "
if [ `which sudo` ];
  then echo "OK";
  else echo "failed
Please install sudo-package/binary!
"
exit 1
fi

# Get accountname to create
CHROOT_USERNAME=$1

if ! [ -z "$2" ]; then
  SHELL=$2
else
  SHELL=/bin/chroot-shell
fi

if ! [ -z "$3" ]; then
  JAILPATH=$3
else
  JAILPATH=/home/jail
fi

# Exit if user already exists
id $CHROOT_USERNAME > /dev/null 2>&1 && { echo "User exists."; echo "Exiting."; exit 1; }

# Create $SHELL (shell for jailed accounts)
echo "Creating $SHELL"
echo '#!/bin/sh' > $SHELL
echo "`which sudo` `which chroot` $JAILPATH /bin/su - \$USER" \"\$@\" >> $SHELL
chmod 755 $SHELL

# make common jail for everybody if inexistent
if [ ! -d $JAILPATH ]; then
  mkdir -p $JAILPATH
  echo "Creating $JAILPATH"
fi
cd $JAILPATH

# Create directories in jail that do not exist yet
JAILDIRS="dev etc etc/pam.d bin home sbin usr usr/bin"
for directory in $JAILDIRS; do
  if [ ! -d "$JAILPATH/$directory" ]; then
    mkdir $JAILPATH/"$directory"
    echo "Creating $JAILPATH/$directory"
  fi
done
echo

# Comment in the following lines if your apache can't read the directories and
# uses the security contexts
# Fix security contexts so Apache can read files
#CHCON=$(`which chcon`)
#if [ -n "$CHCON" ] && [ -x $CHCON ]; then
#    $CHCON -t home_root_t $JAILPATH/home
#    $CHCON -t user_home_dir_t $JAILPATH/home/$CHROOT_USERNAME
#fi

# Creating necessary devices
[ -r $JAILPATH/dev/urandom ] || mknod $JAILPATH/dev/urandom c 1 9
[ -r $JAILPATH/dev/null ]    || mknod $JAILPATH/dev/null    c 1 3
[ -r $JAILPATH/dev/zero ]    || mknod $JAILPATH/dev/zero    c 1 5
[ -r $JAILPATH/dev/tty ]     || mknod $JAILPATH/dev/tty     c 5 0 && chmod 666 $JAILPATH/dev/tty

# if we only want to update the files in the jail
# skip the creation of the new account
if [ "$1" != "update" ]; then

# Modifiy /etc/sudoers to enable chroot-ing for users
# must be removed by hand if account is deleted
echo "Modifying /etc/sudoers"
echo "$CHROOT_USERNAME       ALL=NOPASSWD: `which chroot`, /bin/su - $CHROOT_USERNAME" >> /etc/sudoers

# Define HomeDir for simple referencing
HOMEDIR="$JAILPATH/home/$CHROOT_USERNAME"

# Create new account, setting $SHELL to the above created script and
# $HOME to $JAILPATH/home/*
echo "Adding User \"$CHROOT_USERNAME\" to system"
useradd -m -d "$HOMEDIR" -s "$SHELL" $CHROOT_USERNAME && chmod 700 "$HOMEDIR"
# Enter password for new account
passwd $CHROOT_USERNAME
echo

# Create /usr/bin/groups in the jail
echo "#!/bin/bash" > usr/bin/groups
echo "id -Gn" >> usr/bin/groups
chmod 755 usr/bin/groups

# Add users to etc/passwd
#
# check if file exists (ie we are not called for the first time)
# if yes skip root's entry and do not overwrite the file
if [ ! -f etc/passwd ]; then
 grep /etc/passwd -e "^root" > etc/passwd
fi
if [ ! -f etc/group ]; then
 grep /etc/group -e "^root" > etc/group
# add the group for all users to etc/group (otherwise there is a nasty error
# message and probably because of that changing directories doesn't work with
# winSCP)
 grep /etc/group -e "^users" > etc/group
fi

# grep the username which was given to us from /etc/passwd and add it
# to ./etc/passwd replacing the $HOME with the directory as it will then
# appear in the jail
echo "Adding User $CHROOT_USERNAME to jail"
grep -e "^$CHROOT_USERNAME:" /etc/passwd | \
 sed -e "s#$JAILPATH##"      \
     -e "s#$SHELL#/bin/bash#"  >> etc/passwd

# if the system uses one account/one group we write the
# account's group to etc/group
grep -e "^$CHROOT_USERNAME:" /etc/group >> etc/group

# write the user's line from /etc/shadow to /home/jail/etc/shadow
grep -e "^$CHROOT_USERNAME:" /etc/shadow >> etc/shadow

# endif for =! update
fi

# Copy the apps and the related libs
echo "Copying necessary library-files to jail (may take some time)"

# The original code worked fine on RedHat 7.3, but did not on FC3.
# On FC3, when the 'ldd' is done, there is a 'linux-gate.so.1' that
# points to nothing (or a 90xb.....), and it also does not pick up
# some files that start with a '/'. To fix this, I am doing the ldd
# to a file called ldlist, then going back into the file and pulling
# out the libs that start with '/'
#
# Randy K.
#
if [ -x /root/ldlist ]; then
   mv /root/ldlist /root/ldlist.bak
fi

for app in $APPS;  do

    # First of all, check that this application exists
    if [ -x $app ]; then
        # Check that the directory exists; create it if not.
        app_path=`echo $app | sed -e 's#\(.\+\)/[^/]\+#\1#'`
        if ! [ -d .$app_path ]; then
            mkdir -p .$app_path
        fi

        cp -p $app .$app

        # get list of necessary libraries
        ldd $app >> /root/ldlist
    fi
done

# Clear out any old temporary file before we start
if [ -e /root/ldlist2 ]; then
    rm /root/ldlist2
fi
for libs in `cat /root/ldlist`; do
   frst_char="`echo $libs | cut -c1`"
   if [ "$frst_char" = "/" ]; then
     echo "$libs" >> /root/ldlist2
   fi
done
for lib in `cat /root/ldlist2`; do
            mkdir -p .`dirname $lib` > /dev/null 2>&1
            cp $lib .$lib
done

#
# Now, cleanup the 2 files we created for the library list
#
/bin/rm -f /root/ldlist
/bin/rm -f /root/ldlist2

# Necessary files that are not listed by ldd
cp /lib/libnss_compat.so.2 /lib/libnsl.so.1 /lib/libnss_files.so.2 /lib/libcap.so.1 ./lib/

# if you are using PAM you need stuff from /etc/pam.d/ in the jail,
echo "Copying files from /etc/pam.d/ to jail"
cp /etc/pam.d/* ./etc/pam.d/

# ...and of course the PAM-modules...
echo "Copying PAM-Modules to jail"
cp -r /lib/security ./lib/

# ...and something else useful for PAM
#echo "Copying /etc/security to jail"
cp -r /etc/security ./etc/
cp /etc/login.defs ./etc/


Но както може би се досещата имам  проблем.
След като испълня скрипта ./make_chroot_jail.sh potrebitel /bin/bash /home/jail/potrebitel
всичко би трябвало да е наред но след това с тоя user мога да си се разхождам на всякъде което не би трябвало да става.
Ще се радвам ако някой помогне.
Дистрибуция Дебиан
Поздрави.


Титла: user в chroot jail
Публикувано от: Agent_SMITH в Feb 28, 2006, 09:40
Местя темата в секция за напреднали. Струва ми се тук ще получиш повече отговори ;)


Титла: user в chroot jail
Публикувано от: ohubohu в Feb 28, 2006, 10:20
А идеята за "restricted shell" не ти ли върши работа? Потребителя няма да може да излиза от $home, и няма да може да изпълнява команди започващи с "/". Ще може да изпълнява командите намиращи се в $PATH.

Не знам за какви цели ти е неоходимо :(

Редакция: Видях целите ти :) В такава ситуация аз бих ползвал "restricted shell".

Успех!


Титла: user в chroot jail
Публикувано от: Pulear в Mar 01, 2006, 17:33
Здравейте намерих решение на проблемa
а то се намира  тук  
ако някой се интересува да погленде.
Чао.
Edit:ohubohu мерси за предложението но целта ми беше да разбера  как става цялата магия с chroot jail.


Титла: user в chroot jail
Публикувано от: в Mar 01, 2006, 19:40
Ей тази тема е образец за категория "къде го чукаш, къде се пука".
С решението на проблема направо къртим мивки.


Титла: user в chroot jail
Публикувано от: Pulear в Mar 05, 2006, 02:48
rpetrov
не ми стана ясно какво не хареса в решението на проблема?
ето още един вариянт.
Първо се инсталира това
като роот след това скрипта който в предния пост съм пастнал
се стартира така ./make_chroot_jail потребител /usr/sbin/jk_chrootsh /home/chroot
и после вече се следват инструкциите на скрипта.
поздрави.


Титла: user в chroot jail
Публикувано от: в Mar 05, 2006, 03:03
i predishniq script raboti samo4e ti si zadal greshen parametar pri addvaneto na user...
Az polzvam tozi script ..toi si pravi shell scripta i po4ti vsi4ko kato cqlo.Edistveno ti trqbva da si kopirash programite koito iskash da razreshish da se polzvat + bibliotekite i neobhodimite za tqh rabota.
Ako beshe pro4el how-toto na scripta 6tesshe da vidish 4e kako napishe ./make_chroot_jail.sh to si pravi shell scripta i si addva posle usera da go plzva za da se izvurshva pravilno chrootvaneto.raboti bez probelem
Liubbopiten sam  za restricetd shell predlojenieto ako oje pove4ko svetlina da se v mukne v tunela po nego :)


Титла: user в chroot jail
Публикувано от: Pulear в Mar 05, 2006, 16:56
Здравейте,
възникна друг проблем относно позволенията в chroot jail
та ето го и самия проблем.
Попринцип потребителя който съм поставил в chroot би трябвало да може да пуска pptpd и pptp самото пптп си го пуска но след като му задам параметри за да се върже ми дава следната грешка.
Тази грешка я получавам като стартирам пптп така.
/usr/sbin/pptp 192.168.0.1 remotename 192.168.0.1 name (Потребителското име) noauth
anon warn[pptp_gre_bind:pptp_gre.c:82]: socket: Operation not permitted
anon fatal[main:pptp.c:251]: Cannot bind GRE socket, aborting.
А когато стартирам само пптп без никъкви параметри
си го отваря.
ето ... /usr/sbin/pptp
pptp-linux version 1.5.0
Usage:
  ./pptp <hostname> [<pptp options>] [[--] <pppd options>]
etc...etc...
а pptpd когато се помъча да го стартирам виждам това.
но аз вече копирах libwrap.so.0 в /lib/
 ./pptpd
./pptpd: error while loading shared libraries: libwrap.so.0: cannot open shared object file: No such file or directory

Edit:pptpd -то го оправих вече проблема беше че по инерция съм копирал libwrap.so.0  с  -r
Благодаря предварително.