CentOS 5 SSH+SFTP for remote access and secure file transfers [OpenSSH]

This how-to will show you how to configure:

  • Remote access over SSH via OpenSSH
    • Secure, password-less authentication
    • Optional: OpenSSH 5.4p1 to allow restrict shell access and jail users by group
  • Secure file transfers over SFTP

Configuring OpenSSH

openssh-server is already installed by default, it just needs to be configured. We will disable root logins as well as all password-based logins in favour of the more secure public key authentication. If you do not already have a SSH key, you should take the time to create one now by running ssh-keygen on the computer you will be using to access the server remotely.

The following will configure SSH as described above:

cat << EOF >> /etc/ssh/sshd_config
#
## Customizations ##
# Some of the settings here duplicate defaults, however this is to ensure that
# if for some reason the defaults change in the future, your server's
# configuration will not be affected.

# Do not allow root to login over SSH. If you need to become root, login as your
# regular use and use su - instead.
PermitRootLogin no

# Disable password authentication and enable key authentication. This will
# force users to use key-based authentication which is more secure and will
# protect against some automated brute force attacks on the server. As well,
# this section disables some unneeded authentication types. If you wish to use
# them, modify this section accordingly.
PasswordAuthentication no
PubkeyAuthentication yes
ChallengeResponseAuthentication no
KerberosAuthentication no

# Do not allow TCP or X11 forwarding by default.
AllowTcpForwarding no
X11Forwarding no

# Why give such a large window? If the user has not provided credentials in 30
# seconds, disconnect the user.
LoginGraceTime 30s
EOF

Let's make sure SSH starts on boot, restart the service immediately and finally add the firewall exception for port 22:
chkconfig sshd on
service sshd restart
iptables -I RH-Firewall-1-INPUT 4 -m state --state NEW -m tcp -p tcp --dport 22 -j ACCEPT
service iptables save

Because we have disabled root access over SSH, it is time to create a regular user that you can used to login over ssh and then gain root access:
useradd myusername
passwd myusername
su - myusername
mkdir -m 0700 .ssh
touch .ssh/authorized_keys
chmod 600 .ssh/authorized_keys
exit
restorecon -v -r /home/myusername

Now add the contents of your ~/.ssh/id_rsa.pub file to .ssh/authorized_keys on the server.

Optional (but recommended): Rebuilding OpenSSH 5.x

Although SSH will function perfectly fine with this bare configuration, it is not the most secure possible. CentOS 5 comes with OpenSSH version 4.3p2 which is rather outdated. Instead of using 4.3p2, OpenSSH version 5.4p1 (from Fedora 13) can be rebuilt which offers a slew of new features such as access control via user/group matching and SFTP jailrooting.

yum install fedora-packager
su - myusername
cd ~/rebuilds
fedpkg clone -a openssh
cd openssh
fedpkg switch-branch f13

Before the package can be rebuilt, a few changes need to be made to make it work on CentOS 5. Edit openssh/F-13/openssl.spec and find the line BuildRequires: tcp_wrappers-devel at approximately line number 142. Simply remove the -devel so that the line now reads BuildRequires: tcp_wrappers. Just below, you will also notice a statement BuildRequires: openssl-devel >= 0.9.8j.
Remove the version requirement so that the line reads BuildRequires: openssl-devel. Lastly, near line 178 find the line Requires: pam >= 1.0.1-3 and once again, remove the version requirement so that the line reads Requires: pam.

Now that the RPM spec file has been modified, we also need to change the PAM configuration file as the one from Fedora 13 uses some modules that are not present in CentOS 5:

cat << EOF > sshd.pam
#%PAM-1.0
auth       include      system-auth
account    required     pam_nologin.so
account    include      system-auth
password   include      system-auth
# pam_selinux.so close should be the first session rule
session    required     pam_selinux.so close
session    required     pam_loginuid.so
# pam_selinux.so open should only be followed by sessions to be executed in the user context
session    required     pam_selinux.so open env_params
session    optional     pam_keyinit.so force revoke
session    include      system-auth
EOF

The package is ready to be rebuild for CentOS 5. Execute the following to rebuild and install OpenSSH 5.4p1:

yum install gtk2-devel libX11-devel autoconf automake zlib-devel audit-libs-devel pam-devel fipscheck-devel openssl-devel krb5-devel libedit-devel ncurses-devel libselinux-devel xauth
fedpkg local
exit
rpm -Uhv /home/myusername/rebuilds/openssh/[arch]/openssh-{5,server,clients}*.rpm
rm -f /etc/ssh/sshd_config.rpmnew

Remember to replace [arch] in the second to last command with the appropriate value (most probably i686 for 32-bit machines or x86_64 for 64-bit machines). We can take now advantage of the new features to harden SSH! The configuration segment below will restrict access for members of the serv_sftponly group such that only SFTP access is permitted and those users are jailed to the "web" folder in their home directory (so that they can only upload/download files from their website). Members of the serv_sshall group have full SSH and SFTP access, as well as X11 and TCP forwarding.
mkdir /srv/sftp
groupadd serv_sftponly
groupadd serv_sshall
usermod -a -G serv_sshall myusername
sed -i'' 's|Subsystem\tsftp\t/usr/libexec/openssh/sftp-server|#Subsystem\tsftp\t/usr/libexec/openssh/sftp-server|' /etc/ssh/sshd_config
cat << EOF >> /etc/ssh/sshd_config
#
## Access control ##
# We need to use the internal sftp subsystem
Subsystem       sftp    internal-sftp
# Allow access if user is in these groups
AllowGroups serv_sftponly serv_sshall

# We can't use a path relative to ~ (or %h) because we make the user homes
# /public_html in order to get the chroot above working properly. As a result,
# we need to set an absolute path that will make SSH look in the usual place
# for authorized keys.
AuthorizedKeysFile /home/%u/.ssh/authorized_keys

# Give tunnelling + X11 access to users who are members of group "serv_sshall"
Match group serv_sshall
    X11Forwarding yes
    AllowTcpForwarding yes

# Restrict users who are members of group "serv_sftponly"
Match group serv_sftponly
    # Some settings here may duplicate the global settings, just to be safe.
    #PasswordAuthentication yes
    X11Forwarding no
    AllowTcpForwarding no
    # Force the internal SFTP subsystem and jailroot the user in their home.
    # %u gets substituted with the user name, %h with home
    ForceCommand internal-sftp
    ChrootDirectory /srv/sftp/%u
EOF
service sshd restart

The /srv/sftp/username folder is used instead of the user's entire home because it prevents the user from making any potentially unwanted configuration changes (such as authorizing additional ssh public keys) as well as accidentally deleting files, such as the mail folder which holds all of that domain's emails. One now simply needs to link /srv/sftp/username to the appropriate web folder to jail the user there. For example:
ln -s ../../home/username/web /srv/sftp/username

You do not need to do this manually, as the user setup script will run this for you.

As well, note that the configuration includes the commented line #PasswordAuthentication Yes in the serv_sftponly MatchGroup section. If you so wish, you can uncomment this line to have password authentication enabled ONLY for users of the serv_sftponly group. While password authentication is less secure than public key authentication, it is much more convenient for your clients if you are building a shared hosting machine and if a hacker does gain access because a user had an easy to guess password, they only gain access to a single jailed SFTP client.

Denyhosts

You may be wondering why I haven't included any information about software that can block repeated SSH intrusions such as denyhosts... I have placed this information, along with other server security tips, in the security tutorial (coming soon). Please see it for more information.

Administering the server

Setting up the scripts

The following code will setup the "hosting_user_add" script which can be used to add new hosting users on your server:

mkdir -p /root/bin
cat << EOF > /root/bin/hosting_user_add
#!/bin/sh
# "chown root.root"s are implied, but kept to be safe

if [ -z \$1 ];then
  echo "Usage: \$1 user1 [user2]"
  exit 1
fi

for username in "\$@";do
  read -p "Restrict \$username (make member of serv_sftponly)? [Y/n] " -t 60 -n 1 response
  echo
  if [ "\$response" == "n" ] || [ "\$response" == "N" ];then
    echo "*** Creating normal user \$username"
    useradd -G serv_sshall \$username
  else
    echo "*** Creating restricted user \$username"
    useradd -G serv_sftponly -s /sbin/nologin \$username
  fi
  chown \$username.apache /home/\$username
  chmod 710 /home/\$username
 
  # Set password
  passwd \$username
 
  # Initialize mail storage folder
  mkdir -m 0700 /home/\$username/mail
  chown \$username.\$username /home/\$username/mail
 
  # Initialize web folders
  mkdir -p -m 0755 /home/\$username/web
  chown root.root /home/\$username/web
  # Web: logs
  mkdir -p -m 0750 /home/\$username/web/logs
  chown root.\$username /home/\$username/web/logs
  # Web: offline/private storage
  mkdir -p -m 0755 /home/\$username/web/storage
  chown \$username.\$username /home/\$username/web/storage
  # Web: docroot
  mkdir -m 0755 /home/\$username/web/public_html
  ln -s public_html /home/\$username/web/www
  # make it so they can't remove the symlink
  chown -h root.root /home/\$username/web/www
  chown \$username.\$username /home/\$username/web/public_html
  # Web: PHP error log
  touch /home/\$username/web/php_error_log
  chown \$username.\$username /home/\$username/web/php_error_log
  chattr +u /home/\$username/web/php_error_log

  # Initialize session folder
  mkdir -m 0770 /var/lib/php/session/\$username
  chown root.\$username /var/lib/php/session/\$username

  # SSH: SFTP login
  ln -s ../../home/\$username/web /srv/sftp/\$username

  # SSH: Authorized keys dir
  mkdir -m 0700 /home/\$username/.ssh
  chown \$username.\$username /home/\$username/.ssh
  # Key description here
  echo "your_key_here" >> /home/\$username/.ssh/authorized_keys

  chmod 600 /home/\$username/.ssh/authorized_keys
  chown \$username.\$username /home/\$username/.ssh/authorized_keys
  restorecon -v -r /home/\$username
done
EOF
chmod +x /root/bin/hosting_user_add

You will need to edit /root/bin/hosting_user_add later and replace your_key_here with your own SSH key so that you can login to the account should you ever need to test or do administration work.

Adding a new system account

/root/bin/hosting_user_add new_username

If you are adding many accounts, you can optionally specify more than one username to have each account be created at once. For each user specified, you will be prompted if for both their password and restricted status. Passwords can and should be set randomly because with key-based authentication, they should never have to enter it anyways.

Resources and further reading

Rating: 

Comments

The watches arise in amazing designs and ability to add aggressiveness and adeptness to the men affianced in sports. Sports watches in India enjoys able bazaar a allotment of the sports replique montre hublot lovers and added people. Beat address adulation to get the sports watches online with the bulk of a few clicks. This is the affidavit why a lot of of the online watch food accompany the arch brands of watches online with sports watches prices. You can accretion amazing collections in sports watches including women sports watches, sports watches for kids and more.All these absurd qualities Replique montre Audemars Piguet achieve them account their bulk and branded watches for auction on the bazaar consistently get a complete complete response. Replica watches on the added hand, are not complete blemish or baptize resistant, admission about abounding beneath activity as compared to affluence watches and their gold versions about admission gold replique montre plating instead of any use of solid gold.

That means that each new season has its attendant handbag story coach handbags online lines, cheap ugg boots and Michael Kors Online figuring Coach Factory Outlet Online out michael kors outlet online exactly Coach Online what sac longchamp they Michael Kors Factory Outlet are michael kors outlet online is Michael Kors Outlet a bit coach factory outlet online different Coach Outlet than michael kors outlet deciding ray ban outlet which Coach Outlet new Michael Kors bags coach factory are Coach Outlet the Coach Outlet Store best. Sac Chanel Below, Coach Factory Outlet we've ugg boots assembled ray ban outlet a list of new bags that could have important roles shaping the handbag market in the next few months and why.

Alexander Wang departed Balenciaga to refocus his efforts on his eponymous brand, and michaelkors.us.com this is Coach Outlet Stores the Coach Factory Outlet first Coach Outlet Online big Coach Factory Outlet bag michael kors outlet to Michael Kors Outlet website come ray ban outlet out michael kors outlet of true religion outlet that shift. michael kors outlet The marc jacobs outlet price valentino shoes point ray ban 90% off sale uk is ray ban sunglasses a coach outlet online little cheap ray ban sunglasses bit cheap ray ban uk above some of Wang's other popular bags, so even though this bag is very pretty, I'm interested to see what kind of consumer response it gets.

As this bag is exclusive cheap uggs to coach outlet Bergdorf Louis Vuitton Goodman Michael Kors Outlet Online and Coach Outlet a coach factory outlet limited north face outlet edition,christian louboutin outlet so coach factory outlet snap Valentin Outlet one Coach Outlet Online Store up Chi flat iron before hermes birkin outlet it Michael Kors Outlet Wallet sells pascher hermes out. Coach Outlet Price Michael Kors Outlet Online is $3,500 Michael Kors Outlet via Coach Outlet Online Bergdorf Coach Outlet Goodman coach factory outlet and coach factory outlet you valentino shoes can coach factory outlet buy coach factory online each sac blanc version uggs outlet here: ray ban sunglasses hut pink, yellow, black, red, blue, and gray.Here's a smiling Giada, making her way through LAX with a beautiful white Mansur Gavriel Tote. This is one of the more affordable handbag options we've seen Giada carry; for travel, she usually sticks with Goyard.

The first few days of NYFW have been incredibly hot - the kind of hot that has me staying inside coach outlet stores and cheap oakley sunglasses Vlad valentino rockstud shoes going michael kors outlet out true religion outlet when oakley sunglasses he ray ban outlet can.model de sac chanel For michael kors outlet some chanel porte monnaie reason Michael Kors the valentino shoes heat ralph lauren outlet doesn't ray ban outlet seem oakley sunglasses to oakley sunglasses bother christian louboutin shoes everyone toms shoes else coach factory online as they oakley sunglasses continue valentino outlet to valentino rockstud put ray ban outlet together sac chanel their christian louboutin best ray-ban sunglasses fashion ray ban sunglasses week outfits. Take a look at the best bags of NYFW days one thru three below and check back the rest of the week for more!

Here's Chloë Grace Moretz, leaving her NYC Oakley Sunglasses Outlet hotel Ray ban Sunglasses with a Cheap Ray ban Outlet custom Coach Outlet weekender oakley sunglasses bag cheap oakley outlet made oakley outlet especially ray ban outlet for oakley outlet her ray ban sunglasses by ralph lauren outlet Coach's oakley sunglasses creative cheap oakley sunglasses director, oakley outlet Stuart cheap oakley outlet Vevers. Chloë has shown Coach a lot of love in the past couple years, and the feelings are clearly mutual.

New York Fashion Week is upon us again and over the years we've learned that the content you True Religion Outlet love Valentino Shoes Outlet most sac Louis Vuitton as a Sac Chanel,sac a main whole Oakley Sunglasses is Oakley Sunglasses seeing Ray ban Sunglasses the Giuseppe Zanotti style Cheap Ray ban Outlet and Valentino Shoes bags True Religion Outlet people oakley vault sunglasses carry to True Religion the coach outlet shows. michael kors outlet Of michael kors outlet online course michael kors outlet online we'll coach outlet still coach factory outlet store cover christian louboutin shoes some valentino shoes of coach outlet the abercrombie and fitch best ray ban outlet online handbags being sent down the runway, but there's nothing better than seeing what people wear outside of them.

The first few days of NYFW have been incredibly hot - the kind of hot that has me staying inside (I'm almost 8 months pregnant now!) and Vlad going out when he can. For some reason the heat doesn't seem to bother everyone else as they continue to put together their best fashion week outfits. Take a look at the best bags of NYFW days one thru three below and check back the rest of the week for more!

Cheap Coach Handbags

Friday, September 9 | 10am 5pm [url=http://www.coachonlineoutletstores.us.com]Coach+Factory+Outlet[/url] Coach Outlet

Coach Factory Outlet

Saturday, September 10 | 10am 3pm
[url=http://www.coach-factory-outletonline.us.com]Coach Outlet[/url] Cheap Coach Purses

Michael Kors Outlet Online

Sunday, September 11 | 12pm 4pm
[url=http://www.michaelkorsoutlet-online.us.com]Michael Kors Outlet Online[/url] Cheap Michael Kors

Official Michael Kors Handbags

Monday, September 12 | 10am 5pm KORS [url=http://www.michaelkorshandbagsoutlets.us.com]Official Michael Kors Handbags[/url] Michael Kors Outlet

Coach Outlet

[url=http://www.coachfactoryonlineoutlets.us.com]Coach Factory Online[/url] Coach Outlet Online