• 9 min read
  • 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