# Creating a chrooted sftp server without giving shell

## OmniVector

I found little documentation on this subject, and I'm sure if would be of interest to many people trying to create a secure ftp solution, and this is what I came up with.

Firstly you'll need to emerge the restricted rssh shell

```

emerge rssh

```

To configure it, you'll need add /usr/bin/rssh to the list of accepted shells:

```

echo /usr/bin/rssh >> /etc/shells

```

and you'll want to modify the rssh config and make some minor changes to enable chrooting, scp, and sftp.

/etc/rssh.conf:

```

logfacility = LOG_USER

allowscp

allowsftp

umask = 022

chrootpath="/home"

```

If you wish to disable scp, or sftp independently, just remove the line or comment it out with a #.

Next, we need to build a chroot environment for rssh to work.

This involves copying a few files to our chrooted folder (/home).

```

cd /home

mkdir -p usr/bin

cp /usr/bin/scp usr/bin

cp /usr/bin/rssh usr/bin

mkdir -p usr/libexec

cp /usr/libexec/rssh_chroot_helper usr/libexec

mkdir -p usr/lib/misc

cp /usr/lib/misc/sftp-server usr/lib/misc

```

though we're not quite done copying files yet.  now we need to copy the dependencies of those files.  ldd will tell us what files are needed

```

ldd /usr/bin/scp

        libutil.so.1 => /lib/libutil.so.1 (0x4001c000)

        libz.so.1 => /usr/lib/libz.so.1 (0x4001f000)

        libnsl.so.1 => /lib/libnsl.so.1 (0x4002d000)

        libcrypto.so.0.9.6 => /usr/lib/libcrypto.so.0.9.6 (0x40042000)

        libc.so.6 => /lib/libc.so.6 (0x40106000)

        libdl.so.2 => /lib/libdl.so.2 (0x40235000)

        /lib/ld-linux.so.2 => /lib/ld-linux.so.2 (0x40000000)

```

so now we need to make the necessary folders, and copy the libs needed for scp

```

cd /home

mkdir lib

cp /lib/libutil.so.1 lib

cp /lib/libnsl.so.1 lib

cp /lib/libc.so.6 lib

cp /lib/libdl.so.2 lib

cp /lib/ld-linux.so.2 lib

mkdir -p usr/lib

cp /usr/lib/libz.so.1 usr/lib

cp /usr/lib/libcrypto.so.0.9.6 usr/lib

```

now run ldd on the other files we copied into our chroot environment

```

ldd /usr/bin/rssh

ldd /usr/libexec/rssh_chroot_helper

ldd /usr/lib/misc/sftp-server

```

copy the libraries associated with those files if there are any we didn't already get from scp. note: for me, there were no other dependencies. copying all the dependencies for scp was enough for me. this should be the case for you as well unless your configuration is very different.

the only thing left to do now is create a user and change their shell to /usr/bin/rssh.  there are a couple of ways to do this. you could run superadduser

```

emerge superadduser

superadduser

Login name for new user []: testuser

User ID ('UID') [ defaults to next available ]:

Initial group [ users ]:

Additional groups (comma separated) []:

Home directory [ /home/testuser ]

- Warning: '/home/testuser' already exists !

  Do you wish to change the home directory path? (Y/n)  n

Shell [ /bin/bash ] /usr/bin/rssh

Expiry date (YYYY-MM-DD) []:

```

or simply modify an existing user account

```

usermod -s /usr/bin/rssh testuser

```

finally make sure sshd is running

```

/etc/init.d/sshd status

 * status:  started

```

if not run /etc/init.d/sshd start

and try connecting:

```

sftp testuser@yourip.com

Connecting to yourip.com...

testuser@yourip.com's password:

sftp> ls

.

..

.bash_profile

.bashrc

.qmail

sftp> pwd

Remote working directory: /testuser

sftp> exit

ssh testuser@yourip.com

testuser@yourip.com's password:

This account is restricted to scp or sftp.

If you believe this is in error, please contact your system administrator.

Connection to yourip.com closed.

```

Viola! sftp with chrooting, and no shell allowed!

----------

## carambola5

I don't claim to be a genius in the field of the Linux virtual filesystem or chrooting, but wouldn't it make more sense to link those files rather than copy them?  I believe softlinking won't work because of the chroot jail, but shouldn't hardlinking take care of this?  That way, whenever you update a shared library that had been copied into your chroot, it will automatically update in the chroot jail.

Then again, I could be completely wrong.

----------

## PowerFactor

Well, the problem with hardlinking libs in a chroot to the real libs is that if someone manages to muck them up in the chroot they got the real ones too.  Kinda defeats at least one purpose of the chroot.

----------

## carambola5

 *PowerFactor wrote:*   

> Well, the problem with hardlinking libs in a chroot to the real libs is that if someone manages to muck them up in the chroot they got the real ones too.  Kinda defeats at least one purpose of the chroot.

 

```
chown root:root *.so

chmod 644 *.so
```

Once again, I claim ignorance.  For all I know, this could set the permissions on the original versions too.

----------

## thyrihad

 *Quote:*   

> Well, the problem with hardlinking libs in a chroot to the real libs is that if someone manages to muck them up in the chroot they got the real ones too. Kinda defeats at least one purpose of the chroot.

 

Also, you can't hard link accross partitions, and any sensible secure ftp setup would have /home on a different partition to /usr

----------

## PowerFactor

 *carambola5 wrote:*   

> [
> 
> ```
> chown root:root *.so
> 
> ...

 

Well, I would hope you would set permissions sensibly anyway.  :Wink:   But what happens in the extreme case where someone manages find a hole and get a root shell.  As I understand it that is one of the main purposes of a chroot, to contain such an exploit. But I'm no expert on such things either.

----------

## sschlueter

I think I have set up the chroot environment just as you said and sftp seems to be working fine but scp doesn't. It says "unknown user" followed by the uid of the user that I'm trying to log on as.

I have even created etc/passwd and etc/shadow (each containing a single line for that user) inside the chroot but this doesn't help. 

Any ideas what I'm doing wrong here?

----------

## s0da

ey guys... this topic was very helpful to me... thanks! i would to know how to configure the stuff with shell access included... actually i would like to provide "shell only" access. currentyl, i'm not interested in providing "scp" and "sftp" access. sorry for my ignorance i'm a complete newbie... i would appreciate any suggestion or help anyone can give. Thanks   :Laughing: 

----------

## mstamat

Hi guys,

I just setup rssh for my box. I wanted to use the chroot feature, but I also wanted rssh user to run with the latest installed libs. So I made a little script to make things easier.

Here it is. The script uses ldd to find the runtime dependencies of each of the files listed on the third line of the scripts. The default files seem to work for gentoo, though I didn't tested it extensively. The script also includes a list file in the tarball.

```

#!/bin/bash

#by mstamat: http://forums.gentoo.org/profile.php?mode=viewprofile&u=1205

files="/usr/bin/scp /usr/lib/misc/sftp-server /usr/libexec/rssh_chroot_helper"

tarball="chroot_tarball.tar"

tarball_listfile=".chroot_tarball_list"

#check if files exist

for i in $files; do

        if ! [ -f "$i" ]; then

                if [ "$missing" = "" ]; then

                        missing="$i"

                else

                        missing="$i $missing"

                fi

        fi

done

if ! [ "$missing" = "" ]; then

        printf "Cannot continue. The following files are missing: %s\n" "$missing"

        exit 1

fi

#check each file for deps

for i in $files; do

        printf "Getting dependencies for %s...\n" "$i"

        newdeps=$(ldd "$i" | gawk -F' |=>|\t' '{print $5}')

        if echo $newdeps | grep -q " not " ; then

                printf "Unresolved dependencies for %s. " "$i"

                printf "Run: 'ldd %s' to see the details.\n" "$i"

                exit 1;

        fi

        if [ "$alldeps" = "" ]; then

                alldeps="$newdeps"

        else

                alldeps="$newdeps $alldeps"

        fi

done

printf "\nAll needed dependencies found... Creating tarball...\n"

for i in $alldeps $files; do

        echo "$i"

done | sort | uniq > "$tarball_listfile"

#create tarball

tar cvhf "$tarball" $(cat "$tarball_listfile")

#remove slashes from list file and append it to tarball

sed -i 's/^\///'  "$tarball_listfile"

tar rvf "$tarball" "$tarball_listfile"

#remove list file

rm -f "$tarball_listfile"

```

When you first time configure rssh, you run the script and extract the created tarball in the directory where rssh chroots. 

After an update that affects rssh (rssh itself, openssh, libc etc), you follow these steps to update the files used from chrooted rssh:

cd /my/chroot/dir

rm -rf $(cat .chroot_tarball_list)

tar xvf /path/to/new/tarball/chroot_tarball.tar

And you are done   :Smile: 

----------

## dmck

I followed exactly what you said to do, and it won't authenticate me via sftp, or ssh...

if i do an sftp testuser@localhost...

it asks me for a password 3 times and then asks for testuser@localhosts's password, and then fails...

any ideas?

-dave

----------

## dmck

N/M...i'm just an idiot, and forgot to allow the new user and group in my sshd.conf..

 :Embarassed: 

- dave

----------

## Steffen

Just a quick note for people trying to follow this nice tutorial. I had to copy /lib/ld-linux.so.2 to the chroot, because it it used by rssh!

```
# ldd /usr/bin/rssh

libc.so.6 => /lib/libc.so.6 (0x4002b000)

/lib/ld-linux.so.2 => /lib/ld-linux.so.2 (0x40000000)
```

----------

## Cicero

 *sschlueter wrote:*   

> I think I have set up the chroot environment just as you said and sftp seems to be working fine but scp doesn't. It says "unknown user" followed by the uid of the user that I'm trying to log on as.
> 
> I have even created etc/passwd and etc/shadow (each containing a single line for that user) inside the chroot but this doesn't help. 
> 
> Any ideas what I'm doing wrong here?

 

I'm having the same problem, but have yet to figure it out. A bit of help, anyone?

----------

## Steffen

 *Cicero wrote:*   

>  *sschlueter wrote:*   I think I have set up the chroot environment just as you said and sftp seems to be working fine but scp doesn't. It says "unknown user" followed by the uid of the user that I'm trying to log on as.
> 
> I have even created etc/passwd and etc/shadow (each containing a single line for that user) inside the chroot but this doesn't help. 
> 
> Any ideas what I'm doing wrong here? 
> ...

 The same thing happens for me, too. I didn't even notice it, because I'm mainly interested in SFTP.

----------

## Cicero

I want to use CVS over it, so I suppose I need scp.

----------

## Steffen

I'm sorry, but I'm not an expert and unfortunately do not know a solution.  :Sad: 

----------

## rojaro

Like Scotty said on StarTrek (i think it was in "The Final Frontier"): "How often do i have to tell you people - Always use the right tool for the right Job!"

This is also pretty much true for this case. scponly (net-misc/scponly) does IMHO a much better job in providing this kind of scp service. It provides chroot support out of the box, it has rsync support and is compatible to kind of sftp clients (such as gFTP, the Windows Commander SCP plug-in and also WinSCP), provides a pretty nice logging facility and it doesnt need much memory. I use it pretty much to give selected people access to my CVS server as well as providing an anonymous SFTP service.

----------

## Cicero

It doesn't seem to come with chroot functionality in portage.

----------

## rojaro

right, the "--enable-chrooted-binary" configure flag is missing plus the "make jail" ... but thats fairly easy to enable - just edit the ebuild, emerge and it should work with chroot support.

----------

## Steffen

I think I've found the solution for the "SCP does not work with RSSH" problem!  :Smile: 

The file CHROOT that comes with RSSH states:

[quote]You may need to copy additional libraries, if your system depends upon them for authentication.  For example, in my testing, I needed to copy /lib/libnss_files.so.? into the chroot jail.  Without it, the scp command failed, complaining that my user ID was an unknown user.  If you use LDAP authentication on the server, you will probably need to also copy libnss_ldap.so.? into your chroot jail.[/code]

So I tried it with all /lib/libnss_* files and finally found out that on my Gentoo system (and probably yours) you have to copy /lib/libnss_compat.so.2 into your chroot jail to make SCP work with RSSH!

Edit: I forgot to say that I had to copy my /etc/passwd file into the chroot, too. I don't know, but this makes SCP a bit less attractive for me than SFTP...

----------

## leon_73

Hi,

first of all, thank foe the very well done guide!  :Very Happy: 

Second, just a silly question...

What is the rssh_chroot_helper???

 *OmniVector wrote:*   

> ldd /usr/libexec/rssh_chroot_helper

 

I don't have it!  :Shocked: 

Leo

----------

## Steffen

It's in /usr/lib/misc/ on my system.

----------

## leon_73

 *Steffen wrote:*   

> It's in /usr/lib/misc/ on my system.

 

Found! but what it is for???

It has no man or something else?

Leo

----------

## Cicero

 *rojaro wrote:*   

> right, the "--enable-chrooted-binary" configure flag is missing plus the "make jail" ... but thats fairly easy to enable - just edit the ebuild, emerge and it should work with chroot support.

 

Great, why don't you file a bug report? And why wasn't this already done? I thought gentoo people liked chrooting.

----------

## Cicero

Well, I got rssh working with scp, but cvs gives the "this account restricted to scp and sftp" message. I thought cvs used scp, so why is is acting like it's trying to get a shell? How can I get this to work?

----------

## Cicero

After much research and hard work on this:

https://bugs.gentoo.org/show_bug.cgi?id=33118

Please try it out!

----------

## DArtagnan

 *OmniVector wrote:*   

> I found little documentation on this subject, and I'm sure if would be of interest to many people trying to create a secure ftp solution, and this is what I came up with.
> 
> Firstly you'll need to emerge the restricted rssh shell
> 
> ```
> ...

 

Also please add this line to your howto in order to make it perfect  :Smile: )

```

# cp /lib/libcrypt.so.1 /home/lib/

```

I could not have the chroot working without this line!

----------

## Cicero

 *Cicero wrote:*   

> After much research and hard work on this:
> 
> https://bugs.gentoo.org/show_bug.cgi?id=33118
> 
> Please try it out!

 

For those too lazy to click on the link without knowing what it is, I made a patch for rssh that added cvs support.

----------

## Cicero

Eh, forget it. It's been brutally rejected.

----------

## DArtagnan

Any 1 can understand why I can this error: "user livius attempted to execute forbidden commands" ???

Thanks

My /etc/passw:

```

livius:x:1003:501:Voicu Liviu,507,5881253,6310714,067424004:/liviu:/usr/local/bin/rssh

```

My rssh.conf:

```

[root@ayelet liviu]# cat /usr/local/etc/rssh.conf

# This is the default rssh config file

# set the log facility.  "LOG_USER" and "user" are equivalent.

logfacility = LOG_USER # you can use comments at end of line

# Leave these both uncommented to make the default action for rssh to lock

# users out completely...

allowscp

allowsftp

# set the default umask

umask = 022

# If you want to chroot users, use this to set the directory

# if you DO NOT want to chroot users, LEAVE THIS COMMENTED OUT.

# Quotes not required unless path contains a space...

#chrootpath="/usr/local/chroot dir"

##########################################

# EXAMPLES of configuring per-user options

user=livius:077:11:/liviu

```

From logfile:

```

Nov 20 11:35:34 ayelet rssh[23060]: allowing sftp to all users

Nov 20 11:35:34 ayelet rssh[23060]: setting umask to 022

Nov 20 11:35:34 ayelet rssh[23060]: line 21: configuring user livius

Nov 20 11:35:34 ayelet rssh[23060]: setting livius's umask to 077

Nov 20 11:35:34 ayelet rssh[23060]: allowing scp to user livius

Nov 20 11:35:34 ayelet rssh[23060]: allowing sftp to user livius

Nov 20 11:35:34 ayelet rssh[23060]: chrooting livius to /liviu

Nov 20 11:35:34 ayelet rssh[23060]: user livius attempted to execute forbidden commands

Nov 20 11:35:34 ayelet rssh[23060]: command: /usr/libexec/openssh/sftp-server

Nov 20 11:35:34 ayelet sshd(pam_unix)[23059]: session closed for user livius

```

----------

## Zidge

I  have the exact same problem

does anyone find the solution ?

----------

## nulltype

rssh 2.2 has been released, adding cvs, rdist and rsync support, not sure when it will be added to portage though.

----------

## nulltype

It appears to have a minor bug, I have submitted a patch to the author.  If anyone uses it, just don't use user= lines in your rssh.conf

----------

## cbock

followed the directions in the op and it's working nicely. 

thanks.

----------

## BoBoeBoe

I've setup rssh as explained above and this works fine with a regular directory structure. However I have a directory structure like

/data/symlink1

/data/symlink2

.......

Now I want my rssh-user to be able to access all symlinked subdirectories under /data however the rssh-user cannot access the symlinked subdirectories.

----------

## danpixley

 *Steffen wrote:*   

> 
> 
> Edit: I forgot to say that I had to copy my /etc/passwd file into the chroot, too. I don't know, but this makes SCP a bit less attractive for me than SFTP...

 

You only need an entry in passwd for the user.  Everything else from your original passwd file can be removed.

Dan

----------

## Alapan

Has anyone tried using this method for an AMD64 system? The rssh package is not available for amd64 and I am wondering what the possible problems are.

----------

## Alapan

Ok I tried to see if I could make it work on my system anyway ...

I could compile and install fine; no problems there. For my test user; the rssh shell does provide me with restricted shell usage. However sftp does not seem to work at all - it is almost as if rssh is refusing sftp itself. Sftp itself works for unresticted users.

From another linux machine; the command

```
sftp testuser@mymachine
```

asks for my password and then gives me a "connection closed" message. If I try using winscp for example, I get the following message.

```

Connection has been unexpectedly closed. Server sent command exit status 0.

```

Any ideas on how I could make this work?

----------

## Gavinv

For all who have implemented the chroot, beware of a user hard linking a setuid program into the chroot.

The user can then create their own fake supporting files (e.g. /etc/passwd), and the setuid program would use these files thinking they are the real ones.  Then, if the user can use this setuid system program to gain root privileges, they can create a new setuid root program that does not require a chroot jail to gain root privileges ..

There are other pitfalls to using chroot.

grsecurity.org provides more information.

----------

## milkypostman

when i setup my chroot jail i made all the files root.root owned.  meaning... they have no way of overwritting their /etc/passwd file.  i think that fixes the problem above.  just make sure that every file except for what you want them to be able to manage has your information.  

if that were the case anyways, then why couldn't i goto any computer, set a chroot then develop a setuid program thats'd faked out?  I don't know a lot about chroot but after you chroot aren't you kinda stuck anyways?

----------

## colonel_dolphin

```
info chroot
```

"On many systems, only the super-user can do this." (for good reasons!)

Try logging in as an ordinary user and hard linking a setuid program somewhere under your control.  If you own the parent directory containing the files owned by root, then you can replace those files with your own.  If you can also create a fake /etc/passwd in the chroot directory ..

grsecurity addresses some vulnerabilities associated with using chroot.

----------

## GurliGebis

I cannot get this working.

I have users like thing-001, thing-002 etc.

I want to chroot users into /var/www/thing-00X os they can upload thier webpage via SCP/SFTP, how should I do that.

By the way, the helper binary is placed another place in new versions of rssh.

----------

## colonel_dolphin

Try emerging this one ..  *rojaro wrote:*   

> .. scponly ..

 

----------

## GurliGebis

emerged scponly, but how do I configure it?   :Shocked: 

----------

## j-m

 *GurliGebis wrote:*   

> emerged scponly, but how do I configure it?  

 

First of all, you need scponly-3.11-r2 (unstable but should be stable in one day or so). Previous version do NOT support chrooted SFTP. 

Basically everything is configured. There is a directory /home/scponly which includes all files needed for successful chrooted SFTP. If you want your users to only be able to SFTP via SSH and you don´t want to allow them work interactively in shell, then add them with /sbin/scponlyc as their shell, copy all subdirectories (except incoming) from /home/scponly to their home directory and create a writeable subdirectory for them in their home. 

That´s it.   :Very Happy: 

----------

## GurliGebis

Okay, that works, is there a way to place the folders somewhere so the user only sees the folder I create for him to upload in?

----------

## j-m

 *GurliGebis wrote:*   

> Okay, that works, is there a way to place the folders somewhere so the user only sees the folder I create for him to upload in?

 

No, this is not possible. The dirs make up the filesystem hierarchy needed for chroot to work and MUST be placed in the chrooted home directory. I don´t see the point why you need this anyway. They are NOT user writeable anyway.

----------

## GurliGebis

to avoid confusing the users that does not know about unix

----------

## j-m

 *GurliGebis wrote:*   

> to avoid confusing the users that does not know about unix

 

Ok, you can´t do that.  Period.   :Wink: 

----------

## johanseg

When I run ldd /usr/bin/scp it shows a dependency for linux-gate.so.1 but it doesn't state where it is.

```
# ldd /usr/bin/scp

        linux-gate.so.1 =>  (0xffffe000)

        libresolv.so.2 => /lib/libresolv.so.2 (0xb7fcf000)

        libcrypto.so.0.9.7 => /usr/lib/libcrypto.so.0.9.7 (0xb7ed3000)

        libutil.so.1 => /lib/libutil.so.1 (0xb7ed0000)

        libz.so.1 => /lib/libz.so.1 (0xb7ebf000)

        libnsl.so.1 => /lib/libnsl.so.1 (0xb7eaa000)

        libcrypt.so.1 => /lib/libcrypt.so.1 (0xb7e7d000)

        libc.so.6 => /lib/libc.so.6 (0xb7d6b000)

        libdl.so.2 => /lib/libdl.so.2 (0xb7d68000)

        /lib/ld-linux.so.2 => /lib/ld-linux.so.2 (0xb7fea000)

```

What is linux-gate.so.1 and where is it?

----------

## colonel_dolphin

# emerge sys-apps/slocate

# man slocate

# slocate linux-gate

.. something ..

# qpkg -f <full path of file returned above>

----------

## wjholden

slocate linux-gate doesn't return any output and I have the same problem as above:

```
bash-2.05b# ldd /usr/bin/scp

        linux-gate.so.1 =>  (0xffffe000)

        libresolv.so.2 => /lib/libresolv.so.2 (0x40037000)

        libcrypto.so.0.9.7 => /usr/lib/libcrypto.so.0.9.7 (0x40048000)

        libutil.so.1 => /lib/libutil.so.1 (0x40144000)

        libz.so.1 => /lib/libz.so.1 (0x40148000)

        libnsl.so.1 => /lib/libnsl.so.1 (0x40158000)

        libcrypt.so.1 => /lib/libcrypt.so.1 (0x4016d000)

        libc.so.6 => /lib/libc.so.6 (0x4019a000)

        libdl.so.2 => /lib/libdl.so.2 (0x402ad000)

        /lib/ld-linux.so.2 => /lib/ld-linux.so.2 (0x40000000)
```

----------

## Gavinv

If you are still using rssh with a chroot'ed install, then it might be possible for a user to gain root privileges on your system  :Exclamation: 

http://security.gentoo.org/glsa/glsa-200412-01.xml

 *Gavinv wrote:*   

> For all who have implemented the chroot, beware of a user hard linking a setuid program into the chroot.
> 
> The user can then create their own fake supporting files (e.g. /etc/passwd), and the setuid program would use these files thinking they are the real ones.  Then, if the user can use this setuid system program to gain root privileges, they can create a new setuid root program that does not require a chroot jail to gain root privileges ..
> 
> There are other pitfalls to using chroot.
> ...

 

----------

## GentooBox

I get a segmentation fault when i'm trying to connect to the sftp server. (the server segments)

 *Quote:*   

> Jan 26 16:40:07 GentooBox useradd[5526]: new user: name=testuser, uid=1001, gid=100, home=/home/testuser, shell=/usr/bin/rssh
> 
> Jan 26 16:40:08 GentooBox chfn[5527]: changed user `testuser' information
> 
> Jan 26 16:40:16 GentooBox passwd[5528]: password for `testuser' changed by `root'
> ...

 

thats from the logs

I have 64bit

note:

I cant copy the ld-linux file

 *Quote:*   

> 
> 
>         libcrypto.so.0.9.7 => /usr/lib/libcrypto.so.0.9.7 (0x0000002a9566c000)
> 
>         libutil.so.1 => /lib/libutil.so.1 (0x0000002a958a6000)
> ...

 

ld-linux-x86-64 points to nowhere, that means that i dont need to copy file file, right ?

EDIT:

Both the openssh and rssh package support the "static" use flag - can i use that so i dont need to copy all the files ldd finds ?

----------

## jiri.tyr

Here is my owen perl code for generate SSH dependencies for RSSH:

```

#!/usr/bin/perl

use strict;

use warnings;

my $user = $ARGV[0] || 'user_name';

my $path = './rssh';

my @files = ('/usr/lib/misc/rssh_chroot_helper',

             '/usr/lib/misc/sftp-server',

             '/usr/bin/scp',

             '/usr/bin/sftp');

my %struct;

# get library

foreach my $file (@files) {

        if (not -e $file) {

                warn 'File $file doesn\'t exists!';

        }

        my @lines = `ldd $file`;

        foreach my $line (@lines) {

                my @params = split /\s{1}/, $line;

                if ((defined $params[3] and $params[3] =~ /(.+)\/(.+)/) or 

                    (defined $params[1] and $params[1] =~ /(.*)\/(.+)/)) {

                        $struct{$2} = $1;

                }

        }

}

system 'mkdir -p '.$path;

# copy library

foreach my $key (sort keys %struct) {

        system 'mkdir -p '.$path.'/'.$struct{$key};

        system 'cp -f '.$struct{$key}.'/'.$key.' '.$path.'/'.$struct{$key}.'/';

}

# copy executable files

foreach my $file (@files) {

        if ($file =~ /(.+)\/(.+)/) {

                system 'mkdir -p '.$path.'/'.$1;

                system 'cp -f '.$file.' '.$path.'/'.$file;

        }

}

# authentication library

system 'cp -f /lib/libnss_* '.$path.'/lib/';

# etc diretory

system 'mkdir -p '.$path.'/etc';

system 'grep '.$user.' /etc/passwd > '.$path.'/etc/passwd';

system 'cp -f /etc/ld.so.c* '.$path.'/etc/';

# make package

system 'tar cvhf ./rssh_'.$user.'.tar '.$path.' && rm -fr '.$path;

exit 0;

```

----------

## Puca

I've, unfortunatly, emerged world this morning, which has trashed my server. Keep getting Authentication failure problems. I've recopied any dependancies in case soemthing has changed, but I have a bad feeling it's some change in Baselayout that might have messed up rssh or something.. .as you can tell I'm sketchy on the details here... only brought to my attention 40mins ago  :Sad: 

----------

## Puca

Ah got it... was /etc/shells missing 

/usr/bin/rssh

phew !

----------

## gringo

gentoobox -> same segfaults here ! Did you solved this issue compiling static packages ?

TIA

----------

## GentooBox

 *gringo wrote:*   

> gentoobox -> same segfaults here ! Did you solved this issue compiling static packages ?
> 
> TIA

 

nope, still the same problem.

----------

## j-m

I can´t resist:

```

emerge net-misc/scponly && forget all this crap

```

 :Laughing: 

----------

## gringo

thanks, didnt know about this one  :Very Happy: 

but problem persists on amd64, segfauts too  :Sad: 

cheers

----------

## groonie

I use 64bit, too.

Since I never managed to solve the segfault problem, I emerged a 32bit binary from my 32bit gentoo chroot

and it worked again. Not a beautiful solution, but a workin' one!

----------

## Crisis

Anyone been able to get full file transfer logging with this solution?  I compiled openssh with the sftplogging option, but I have only been able to get full logging to work with bash as the shell...

Supposedly rssh and scponly both have logging options of their own, but has anyone been able to get them to actually log file transfers?  If so, can you post example configs/details?  Thanks!

----------

## GoofyHMG

root # superadduser

Login name for new user []: testuser

User ID ('UID') [ defaults to next available ]:

Initial group [ users ]:

Additional groups (comma separated) []:

Home directory [ /home/testuser ]

Shell [ /bin/bash ] /usr/bin/rssh

Expiry date (YYYY-MM-DD) []:

New account will be created as follows:

---------------------------------------

Login name.......:  testusertest

UID..............:  [ Next available ]

Initial group....:  users

Additional groups:  [ None ]

Home directory...:  /home/testusertest

Shell............:  /usr/bin/rssh

Expiry date......:  [ Never ]

This is it... if you want to bail out, hit Control-C.  Otherwise, press

ENTER to go ahead and make the account.

Creating new account...

chfn: Unknown user testusertest

- Warning: an error occurred while setting finger information

passwd: Unknown user testusertest

* WARNING: An error occured while setting the password for

           this account.  Please manually investigate this *

----------

## groovin

anyone actually try a security test of this? i was thinking about opening up my home server to some friends who are pretty geeky... they are pretty knowledgeable with this kinda stuff and a couple of them are capable of rooting a poorly configured box, and though they wont do any damage (i know where they live) to my box, i know they will try to so i figure might as well make it hard for them!

----------

## heimatland

 *Steffen wrote:*   

> I think I've found the solution for the "SCP does not work with RSSH" problem! 
> 
> The file CHROOT that comes with RSSH states:
> 
> You may need to copy additional libraries, if your system depends upon them for authentication.  For example, in my testing, I needed to copy /lib/libnss_files.so.? into the chroot jail.  Without it, the scp command failed, complaining that my user ID was an unknown user.  If you use LDAP authentication on the server, you will probably need to also copy libnss_ldap.so.? into your chroot jail.
> ...

 

anyone having unknown user problem with scp or Exit code 255 with sftp:

what Steffen gave above helped. 

I needed /lib/libnss_compat.so.2 copied to lib/ inside chroot.

Works like a charm then.

Lost half a day to dig it up.

----------

## pumpichank

I solved the problem of having the connection mysteriously close without any further indication in the log files.  The first problem is that you need to configure things so rssh_chroot_helper can syslog in the jail.  With syslog-ng this is easy by adding another source log pointing to /chroot/jail/dev/log

Then I got rssh_chroot_helper to log enough information to discover that I needed an /etc/passwd (and helpfully tho' apparently not required) /etc/group in the chroot.  After adding these, everything worked beautifully.

I put more detail in the wiki HOWTO article.

----------

## humbletech99

I followed the gentoo-wiki article and saw at the bottom a proposed better way without having to redo the libs and have libs in the user's home dirs.

I'm still trying to get this working, I compiled a static openssh with the chroot use flag as well, is the chroot use flag applying the patch from here http://www.minstrel.org.uk/papers/sftp/ ?

Also, does anyone know where to get more info/docs on the chroot use flag and how to make use of it, there is no point in having this patch added to portage if there is no doc on what it gives you and how to use it.

----------

## UgolinoII

I too was following the Minstrel guide, and I had just got to creating a patch from his modified sftp-server.c file.

I copied the ebuild into the overlay directory, and was about to modify it when I came across this line 

```
use chroot && epatch "${FILESDIR}"/openssh-4.3_p1-chroot.patch
```

i checked the patches, whilst they aren;t identical they look to do the same thing.

```
diff -y /var/portage/net-misc/openssh/files/chroot-patch.patch /usr/portage/net-misc/openssh/files/openssh-4.3_p1-chroot.patch #

15a16,22                                                      | http://chrootssh.sourceforge.net/

>  *                                                          |

>  ********************************************************** | --- openssh-4.3p1/session.c

>  * This version modified 08/11/06 by Minstrel <Minstrel@min | +++ openssh-4.3p1/session.c

>  * to provide chroot'd SFTP (see http://www.minstrel.org.uk | @@ -59,6 +59,8 @@

>  *                                                          |  #include "kex.h"

>  * Search for 'Minstrel' in this file to find modifications |  #include "monitor_wrap.h"

>  ********************************************************** |  

47a55,58                                                      | +#define CHROOT

> /* Following single line added by Minstrel */               | +

>                                                             |  #if defined(KRB5) && defined(USE_AFS)

> #define CHROOT                                              |  #include <kafs.h>

>                                                             |  #endif

1206a1218,1250                                                | @@ -1251,6 +1253,11 @@

> /* Start additions by Minstrel */                           |  void

>                                                             |  do_setusercontext(struct passwd *pw)

> #ifdef CHROOT                                               |  {

> void                                                        | +#ifdef CHROOT

> chroot_init(void)                                           | +       char *user_dir;

> {                                                           | +       char *new_root;

>        char *user_dir, *new_root;                           | +#endif /* CHROOT */

>                                                             | +

>        user_dir = getenv("HOME");                           |  #ifndef HAVE_CYGWIN

>        if (!user_dir)                                       |         if (getuid() == 0 || geteuid() == 0)

>                fatal("HOME isn't in environment");          |  #endif /* HAVE_CYGWIN */

>                                                             | @@ -1308,6 +1315,27 @@

>        new_root = user_dir + 1;                             |                         restore_uid();

>                                                             |                 }

>        while ((new_root = strchr(new_root, '.')) != NULL) { |  #endif

>                new_root--;                                  | +

>                if (strncmp(new_root, "/./", 3) == 0) {      | +#ifdef CHROOT

>                        *new_root = '\0';                    | +       user_dir = xstrdup(pw->pw_dir);

>                        new_root += 2;                       | +       new_root = user_dir + 1;

>                                                             | +

>                        if (chroot(user_dir) != 0)           | +       while ((new_root = strchr(new_root, '.')) != NULL) {

>                                fatal("Couldn't chroot to us | +               new_root--;

>                                                             | +               if (strncmp(new_root, "/./", 3) == 0) {

>                        setenv("HOME", new_root, 1);         | +                       *new_root = '\0';

>                        break;                               | +                       new_root += 2;

>                }                                            | +

>                new_root += 2;                               | +                       if(chroot(user_dir) != 0)

>        }                                                    | +                               fatal("Couldn't chroot to use

> }                                                           | +                       pw->pw_dir = new_root;

> #endif /* CHROOT */                                         | +                       break;

>                                                             | +               }

> /* End additions by Minstrel */                             | +

>                                                             | +               new_root += 2;

1272a1317,1326                                                | +       }

> /* Start additions by Minstrel */                           | +#endif /* CHROOT */

>                                                             | +

> #ifdef CHROOT                                               |  # ifdef USE_PAM

>        chroot_init();                                       |                 /*

> #endif                                                      |                  * PAM credentials may take the form of suppl

>       if (setuid(getuid()) != 0)                            |

>               fatal("Couldn't drop privileges: %s", strerro <

>                                                             <

> /* End additions by Minstrel */                             <

>                                                             <

```

so one can only assume that the chroot flag is for exactly the purpose described in the minstrel guide.

more to follow...

----------

## humbletech99

I have my server working and chrooted, but didn't use the chroot flag in openssh, instead I'm using scponly as this will not give a shell.

----------

## mycroes

I think all of this can be done a lot easier (but correc me if I'm wrong)... If you enable USE=static for openssh and rssh you shouldn't need any libraries at all in the chroot. I think the path for scp and sftp-server can be set in the sshd_config, see the example:

```
# override default of no subsystems

Subsystem       sftp    /usr/lib/misc/sftp-server
```

This is in sshd_config by default. So combining these thoughts I think you can make a dir bin in a user's home directory, put all the binaries you need in bin, chroot them in the home directory and you're done... If you're doing this it is also possible to have a /home/chrootbin to which the bin dirs are hardlinked, so you only need to update /home/chrootbin every time you update any of the binaries that you copied to the chroot...

Seems a lot easier too me, but perhaps I'm overlooking something.

Regards,

Michael

----------

## mycroes

 *humbletech99 wrote:*   

> I have my server working and chrooted, but didn't use the chroot flag in openssh, instead I'm using scponly as this will not give a shell.

 

rssh will not give a shell either, but could you explain how you chrooted your scponly? I'm still doubting which way to go, rssh or scponly...

Regards,

Michael

----------

## humbletech99

thanks for the suggestions, using the static use flag was exactly what I did.

although I'm not sure about the symlinking thing, this may allow chroot breaking.... iirc you should not have any links leading outside of your chroot.

I have instead got a basic skel which i can copy over and will simply bashify updates on this.

EDIT: I tried rssh first, but scponly seems the better option. Someone told me rssh was lame so I checked out scponly and it seems to work well and easier. It uses a // in the home dir path to separate the jail and the home dir inside the jail.

----------

## mycroes

 *humbletech99 wrote:*   

> thanks for the suggestions, using the static use flag was exactly what I did.

 

What did you do with it, scponly doesn't have a static use flag, could you explain the contents and configuration of your chroot a bit more? Doesn't have to be a step by step howto, but an outline will be appreciated...

 *humbletech99 wrote:*   

> although I'm not sure about the symlinking thing, this may allow chroot breaking.... iirc you should not have any links leading outside of your chroot.

 

I only partially agree. I wasn't talking about symlinking to the system binaries, but to a copied version in /home. I can't even symlink to system binaries, because they're on a different volume. I'm running a hardened server, I don't think they'll be able to break a lot, and I'm willing to take the risk.

Also, I currently have noexec in /home, my clients are only member of a seperate group and I set umask to 077 so they shouldn't be able to create anything that someone else except root can read, so I doubt if I'm gonna chroot at all... Of course there's write access in /tmp, but /tmp is noexec too. If I were to chroot then I'd also have to add php and apache to the chroot, or else it would be quite useless (php and apache get forked to the user whose content is to be displayed)...

Anyway, I'm still interested in the ways a chroot can be set up, maybe in the future I will have a use for it...

Regards,

Michael

----------

## humbletech99

where are your jails located?

if symlinking jailed bins/libs to /home then noexec may stop the whole thing from working.

where did apache and php come from? you are trying to use sftp to manage a web server?

I created a jail the standard way by recreating a minimal dir structure and then scp makes the chroot call and locks into the jail. This is done by scponly just by setting it to be your shell and then making the home directory of the user /path/to/jail//home/username.

Then you just have to test it to death to make libs work (statically compiling where you can helps)

----------

## mycroes

My jails would've been located in /home/username. I know that noexec would break them, so if I'm going without jails is perhaps more secure because I don't have to worry about any users being able to write anywhere with execute privileges. I use sftp to have clients upload their website...

Regards,

Michael

----------

## humbletech99

err, there is a very good reason to chroot sftp, otherwise they can enumerate all users, look around in your system, steal files etc.

You'd have to do a lot of work to stop them and not all of this is stoppable without breaking your server, hence the chroot requirement.

----------

## mycroes

I don't mind them enumerating users, users will need a private key to log in anyway, so no matter how much users they enumerate, it doesn't make a difference... As for 'stealing files', I don't mind if they steal libraries and binaries, they're compiled form gpl source (at least most of them) so I wouldn't call that stealing... And they're clients. As soon as I notice anything fishy is going on they can say godbye to their account... And last but not least, chrooting sftp won't prevent them from using php to snoop around in the system...

Regards,

Michael

----------

## humbletech99

you underestimate the potential.

but I guess it might end up being too much work for you especially if you have to apache and php as well.

anyway, do what you want, that's fine.

----------

## chrisk2305

Hi Guys!

I'm kinda new to (gentoo)linux and i'm running into problems with the tutorial. Im running Gentoo AMD64.

I also got the connection closed error when i tried to log in from the shell (or winscp)

Then i started logging and here's the error:

```
Sep  5 12:49:29 fileserver sshd(pam_unix)[9352]: session opened for user oneuser by (uid=0)

Sep  5 12:49:29 fileserver sshd[9352]: subsystem request for sftp

Sep  5 12:49:29 fileserver rssh[9353]: setting log facility to LOG_USER

Sep  5 12:49:29 fileserver rssh[9353]: allowing scp to all users

Sep  5 12:49:29 fileserver rssh[9353]: allowing sftp to all users

Sep  5 12:49:29 fileserver rssh[9353]: setting umask to 022

Sep  5 12:49:29 fileserver rssh[9353]: chrooting all users to /home

Sep  5 12:49:29 fileserver rssh[9353]: chroot cmd line: /usr/lib64/misc/rssh_chroot_helper 2 "/usr/lib64/misc/sftp-server"

Sep  5 10:49:29 fileserver rssh_chroot_helper[9353]: new session for oneuser, UID=1002

Sep  5 10:49:29 fileserver rssh_chroot_helper[9353]: user's home dir is /home/oneuser

Sep  5 10:49:29 fileserver rssh_chroot_helper[9353]: chrooted to /home

Sep  5 10:49:29 fileserver rssh_chroot_helper[9353]: changing working directory to /oneuser (inside jail)

Sep  5 10:49:29 fileserver rssh_chroot_helper[9353]: execv() failed, /usr/lib64/misc/sftp-server: No such file or directory

Sep  5 12:49:29 fileserver sshd(pam_unix)[9352]: session closed for user oneuser

```

Don't quite get, because the /usr/lib64/misc/sftp-server file/folder exists?!

Plz help me, thx!

----------

## humbletech99

am I right in reading you have chrooted to just /home?

noob, get a clue, go read some docs on how chroots work. You should not be chrooting to /home.

Hint: Does /home/usr/lib64/misc/sftp-server exist?

 :Rolling Eyes: 

----------

