FTP is dead. Long live SFTP. An interesting alternative to secure ftp. How to jail SFTP users on a CentOS 6

This mini how-to addresses jailing of SFTP users (SFTP = SSH File Transfer Protocol), which means restrict user’s access to their home directory. It will also disable shell login, therefore additional configuration must be done to allow restricted shell access, all finers pointing towards http://olivier.sessink.nl/jailkit/

• Edit your /etc/ssh/sshd_config

• Find the line where /usr/libexec/openssh/sftp-server resides (path is distribution dependant)

• Replace it with internal-sftp. The whole line should look:
» Subsystem sftp internal-sftp

• Create a group “upload” or “sftpusers” – something intuitive. Every user that you want to grant upload access via SFTP must be a member of this group.

• In your sshd_config file add:

Match Group upload
   ChrootDirectory %h
   AllowTCPForwarding no
   X11Forwarding no
   ForceCommand internal-sftp

NB: Further access can be enforced by playing with Match Group X or Match user Y.

• Check for errors by doing a fast
» service sshd reload

• Next, add a group under which we will gather all accounts that we want to allow upload access. I’m going to add a system user (no login) and a group with the same name.
» adduser --system --group upload for Debian
» adduser -M -s /bin/false upload for CentOS

• Issue the following commands
» chown -R root:root /home
» chmod -R 755 /home
» usermod -aG upload user1 ; usermod -aG upload user2 etc.
» chown -R user1:upload /home/user1/directory_you_wish_to_be_writeable
(tip: wildcard is supported, eg chown -R user1:upload /home/user1/*/www )

• At this point you need to service sshd restart and check for any errors.

• Final exam: simply login with FileZilla (SFTP!) or your client of choice and try to cd.

References
• http://serverfault.com/questions/591781/creating-sftp-users-and-jailing-to-chroot-on-centos-user-authentication-error
• http://askubuntu.com/questions/134425/how-can-i-chroot-sftp-only-ssh-users-into-their-homes

SSH configuration explained

### Subsystem sftp /usr/lib/openssh/sftp-server
 # External file transfer daemon to use for sftp requests
 # Distribution specific!
 # Debian: Subsystem sftp /usr/lib/openssh/sftp-server
 # CentOS: Subsystem sftp /usr/libexec/openssh/sftp-server
 #Subsystem sftp /usr/lib/openssh/sftp-server
 #Subsystem sftp /usr/libexec/openssh/sftp-server
#################################
 ### PermitRootLogin
 #################################
 # Permit root to login? ``yes'', ``without-password'',
 # ``forced-commands-only'', or ``no''. The default is ``yes''.
 # If this option is set to ``without-password'', password authenti-
 # cation is disabled for root.
 # If this option is set to ``forced-commands-only'', root login
 # with public key authentication will be allowed, but only if the
 # command option has been specified (which may be useful for taking
 # Specifies whether ~/.ssh/environment and environment= options in
 # ~/.ssh/authorized_keys are processed by sshd(8). The default is
 # ``no''. Enabling environment processing may enable users to
 # bypass access restrictions in some configurations using mecha-
 # nisms such as LD_PRELOAD.
 PermitRootLogin yes
#################################
 ### AllowGroups | DenyGroups
 #################################
 # Allow/deny certain groups to login
 # -----------
 #AllowGroups
 #DenyGroups
#################################
 ### AllowUsers | DenyUsers
 #################################
 # Allow/deny certain members to login
 # ----------
 #AllowUsers
 #DenyUsers
#################################
 ### AcceptEnv
 #################################
 # Accept any environment variables sent by client
 AcceptEnv LC_*
#################################
 ### AdressFamily
 #################################
 # any, inet (ipv4 only), inet 6
 AddressFamily any
#################################
 ### AllowAgentForwarding
 #################################
 # Disabling agent forwarding does not improve security unless users are also denied shell access,
 # as they can always install their own forwarders.
 AllowAgentForwarding no
#################################
 ### Banner
 #################################
 # Message sent to user prior to authentication
 #Banner banner.txt
#################################
 ### ChallengeResponseAuthentication
 #################################
 # Specifies whether challenge-response authentication is allowed (PAM)
 ChallengeResponseAuthentication no
#################################
 ### ChrootDirectory
 #################################
 # Specifies a path to chroot(2) to after authentication. This
 # path, and all its components, must be root-owned directories that
 # are not writable by any other user or group. After the chroot,
 # sshd(8) changes the working directory to the user's home directory.
 # The path may contain the following tokens that are expanded at
 # runtime once the connecting user has been authenticated: %% is
 # replaced by a literal '%', %h is replaced by the home directory
 # of the user being authenticated, and %u is replaced by the user-
 # name of that user.
 # Fast tutorial: http://allanfeid.com/content/creating-chroot-jail-ssh-access
 #ChrootDirectory
#################################
 ### ClientAliveCountMax
 #################################
 # Sets the number of client alive messages (see below) which may be
 # sent without sshd(8) receiving any messages back from the client.
 # If this threshold is reached while client alive messages are
 # being sent, sshd will disconnect the client, terminating the ses-
 # sion. It is important to note that the use of client alive mes-
 # sages is very different from TCPKeepAlive (below). The client
 # alive messages are sent through the encrypted channel and there-
 # fore will not be spoofable. The TCP keepalive option enabled by
 # TCPKeepAlive is spoofable. The client alive mechanism is valu-
 # able when the client or server depend on knowing when a connec-
 # tion has become inactive.
 # The default value is 3. If ClientAliveInterval (see below) is
 # set to 15, and ClientAliveCountMax is left at the default, unre-
 # sponsive SSH clients will be disconnected after approximately 45
 # seconds. This option applies to protocol version 2 only.
 # (ClientAliveCountMax * ClientAliveInterval)
 ClientAliveCountMax 15
#################################
 ### ClientAliveInterval
 #################################
 # Sets a timeout interval in seconds after which if no data has
 # been received from the client, sshd(8) will send a message
 # through the encrypted channel to request a response from the
 # client. The default is 0, indicating that these messages will
 # not be sent to the client. This option applies to protocol ver-
 # sion 2 only.
 ClientAliveInterval 60
#################################
 ### Compression
 #################################
 # Specifies whether compression is allowed, or delayed until the
 # user has authenticated successfully. The argument must be
 # ``yes'', ``delayed'', or ``no''. The default is ``delayed''.
 Compression delayed
#################################
 ### ForceCommand
 #################################
 # Forces the execution of the command specified by ForceCommand,
 # ignoring any command supplied by the client and ~/.ssh/rc if
 # present. The command is invoked by using the user's login shell
 # with the -c option. This applies to shell, command, or subsystem
 # execution. It is most useful inside a Match block. The command
 # originally supplied by the client is available in the
 # SSH_ORIGINAL_COMMAND environment variable. Specifying a command
 # of ``internal-sftp'' will force the use of an in-process sftp
 # server that requires no support files when used with ChrootDirectory.
 #ForceCommand
#################################
 ### GatewayPorts
 #################################
 # Specifies whether remote hosts are allowed to connect to ports
 # forwarded for the client. By default, sshd(8) binds remote port
 # forwardings to the loopback f. This prevents other remote
 # hosts from connecting to forwarded ports. GatewayPorts can be
 # used to specify that sshd should allow remote port forwardings to
 # bind to non-loopback addresses, thus allowing other hosts to con-
 # nect. The argument may be ``no'' to force remote port forward-
 # ings to be available to the local host only, ``yes'' to force
 # remote port forwardings to bind to the wildcard address, or
 # ``clientspecified'' to allow the client to select the address to
 # which the forwarding is bound. The default is ``no''.
 #GatewayPorts
#################################
 ### GSSAPIAuthentication
 #################################
 # Specifies whether user authentication based on GSSAPI is allowed.
 # The default is ``no''. Note that this option applies to protocol
 # version 2 only.
 #################################
 ### GSSAPIKeyExchange
 #################################
 # Specifies whether key exchange based on GSSAPI is allowed. GSSAPI
 # key exchange doesn't rely on ssh keys to verify host identity.
 # The default is ``no''. Note that this option applies to protocol
 # version 2 only.
 #################################
 ### GSSAPICleanupCredentials
 #################################
 # Specifies whether to automatically destroy the user's credentials
 # cache on logout. The default is ``yes''. Note that this option
 # applies to protocol version 2 only.
 #################################
 ### GSSAPIStrictAcceptorCheck
 #################################
 # Determines whether to be strict about the identity of the GSSAPI
 # acceptor a client authenticates against. If ``yes'' then the
 # client must authenticate against the host service on the current
 # hostname. If ``no'' then the client may authenticate against any
 # service key stored in the machine's default store. This facility
 # is provided to assist with operation on multi homed machines.
 # The default is ``yes''. Note that this option applies only to
 # protocol version 2 GSSAPI connections, and setting it to ``no''
 # may only work with recent Kerberos GSSAPI libraries.
 #################################
 ### GSSAPIStoreCredentialsOnRekey
 #################################
 # Controls whether the user's GSSAPI credentials should be updated
 # Specifies whether or not the server will attempt to perform a
 # reverse name lookup when matching the name in the ~/.shosts,
 # ~/.rhosts, and /etc/hosts.equiv files during
 # HostbasedAuthentication. A setting of ``yes'' means that sshd(8)
 # uses the name supplied by the client rather than attempting to
 # resolve the name from the TCP connection itself. The default is
 # ``no''.
 GSSAPIAuthentication no
#################################
 ### IgnoreRhosts
 #################################
 # Specifies that .rhosts and .shosts files will not be used in
 # RhostsRSAAuthentication or HostbasedAuthentication.
 # /etc/hosts.equiv and /etc/ssh/shosts.equiv are still used. The
 # default is ``yes''.
 IgnoreRhosts yes
#################################
 ### IgnoreUserKnownHosts
 #################################
 # Specifies whether sshd(8) should ignore the user's
 # ~/.ssh/known_hosts during RhostsRSAAuthentication or
 # HostbasedAuthentication. The default is ``no''.
 IgnoreUserKnownHosts no
#################################
 ### HostbasedAuthentication
 #################################
 # Pretty self explanatory
 HostbasedAuthentication no
#################################
 ### KerberosAuthentication
 #################################
 # Specifies whether the password provided by the user for
 # PasswordAuthentication will be validated through the Kerberos
 # KDC. To use this option, the server needs a Kerberos servtab
 # which allows the verification of the KDC's identity. The default
 # is ``no''.
 ### KerberosGetAFSToken
 # If AFS is active and the user has a Kerberos 5 TGT, attempt to
 # acquire an AFS token before accessing the user's home directory.
 # The default is ``no''.
 ### KerberosOrLocalPasswd
 # If password authentication through Kerberos fails then the pass-
 # word will be validated via any additional local mechanism such as
 # /etc/passwd. The default is ``yes''.
 ### KerberosTicketCleanup
 # Specifies whether to automatically destroy the user's ticket
 # cache file on logout. The default is ``yes''.
 KerberosAuthentication no
#################################
 ### KeyRegenerationInterval
 #################################
 # In protocol version 1, the ephemeral server key is automatically
 # regenerated after this many seconds (if it has been used). The
 # purpose of regeneration is to prevent decrypting captured ses-
 # If port is not specified, sshd will listen on the address and all
 # prior Port options specified. The default is to listen on all
 # local addresses. Multiple ListenAddress options are permitted.
 # Additionally, any Port options must precede this option for non-
 # port qualified addresses.
 KeyRegenerationInterval 3600
#################################
 ### LoginGraceTime
 #################################
 # The server disconnects after this time if the user has not suc-
 # cessfully logged in. If the value is 0, there is no time limit.
 # The default is 120 seconds.
 LoginGraceTime 10
#################################
 ### LogLevel
 #################################
 # Gives the verbosity level that is used when logging messages from
 # sshd(8). The possible values are: SILENT, QUIET, FATAL, ERROR,
 # INFO, VERBOSE, DEBUG, DEBUG1, DEBUG2, and DEBUG3. The default is
 # INFO. DEBUG and DEBUG1 are equivalent. DEBUG2 and DEBUG3 each
 # specify higher levels of debugging output. Logging with a DEBUG
 # level violates the privacy of users and is not recommended.
 LogLevel INFO
#################################
 ### MACs
 #################################
 # Specifies the available MAC (message authentication code) algo-
 # rithms. The MAC algorithm is used in protocol version 2 for data
 # integrity protection. Multiple algorithms must be comma-sepa-
 # rated. The default is:
 # hmac-md5,hmac-sha1,umac-64@openssh.com,
 # hmac-ripemd160,hmac-sha1-96,hmac-md5-96
 #MACs
#################################
 ### PasswordAuthentication
 #################################
 # Password authentication. Change to not for key only authentication
 PasswordAuthentication yes
#################################
 ### PermitBlacklistedKeys
 #################################
 # Specifies whether sshd(8) should allow keys recorded in its
 # blacklist of known-compromised keys (see ssh-vulnkey(1)). If
 # ``yes'', then attempts to authenticate with compromised keys will
 # be logged but accepted. If ``no'', then attempts to authenticate
 # with compromised keys will be rejected. The default is ``no''.
 PermitBlacklistedKeys no
#################################
 ### PermitEmptyPasswords
 #################################
 # When password authentication is allowed, it specifies whether the
 # server allows login to accounts with empty password strings. The
 # default is ``no''.
 PermitEmptyPasswords no
#################################
 ### PidFile
 #################################
 PidFile /var/run/sshd.pid
#################################
 ### Port
 #################################
 # Specifies the port number that sshd(8) listens on. The default
 # is 22. Multiple options of this type are permitted. See also
 # ListenAddress below.
 Port 20202
#################################
 ### ListenAddress
 #################################
 # SSH by default will listen on all IP addresses of the machine.
 # Format:
 # ListenAddress 0.0.0.0
 # ListenAddress ::
 #
 # Can be restricted to different ports on different interfaces:
 # Port 2222
 # ListenAddress [myhostname_or_myinternalIPaddress]:22
 # ListenAddress 0.0.0.0
 # The above config listens to port 22 internally, and port 2222 externally (and internally)
 # :: Reroute packets with the help of iptables: http://fatphil.org/linux/ssh_ports.html
 #ListenAddress
#################################
 ### PrintLastLog
 #################################
 # Specifies whether sshd(8) should print the date and time of the
 # last user login when a user logs in interactively. The default
 # is ``yes''.
 PrintLastLog yes
#################################
 ### PrintMotd
 #################################
 # Specifies whether sshd(8) should print /etc/motd when a user logs
 # in interactively. (On some systems it is also printed by the
 # shell, /etc/profile, or equivalent.) The default is ``yes''.
 PrintMotd yes
#################################
 ### Protocol
 #################################
 # Specifies the protocol versions sshd(8) supports. The possible
 # values are '1' and '2'. Multiple versions must be comma-sepa-
 # rated. The default is ``2,1''. Note that the order of the pro-
 # tocol list does not indicate preference, because the client
 # selects among multiple protocol versions offered by the server.
 # Specifying ``2,1'' is identical to ``1,2''.
 Protocol 2
#################################
 ### RhostsRSAAuthentication
 #################################
 # Specifies whether rhosts or /etc/hosts.equiv authentication
 # together with successful RSA host authentication is allowed. The
 # default is ``no''. This option applies to protocol version 1
 # only.
 RhostsRSAAuthentication no
#################################
 ### RSAAuthentication
 #################################
 # Specifies whether pure RSA authentication is allowed. The
 # default is ``yes''. This option applies to protocol version 1
 # only.
 RSAAuthentication yes
#################################
 ### ServerKeyBits
 #################################
 # Defines the number of bits in the ephemeral protocol version 1
 # server key. The minimum value is 512, and the default is 1024.
 ServerKeyBits 2048
#################################
 ### StrictModes
 #################################
 # Specifies whether sshd(8) should check file modes and ownership
 # Alternately the name ``internal-sftp'' implements an in-process
 # ``sftp'' server. This may simplify configurations using
 # ChrootDirectory to force a different filesystem root on clients.
 # By default no subsystems are defined. Note that this option
 # applies to protocol version 2 only.
 StrictModes yes
#################################
 ### SyslogFacility
 #################################
 # Gives the facility code that is used when logging messages from
 # sshd(8). The possible values are: DAEMON, USER, AUTH, LOCAL0,
 # LOCAL1, LOCAL2, LOCAL3, LOCAL4, LOCAL5, LOCAL6, LOCAL7. The
 # default is AUTH.
 SyslogFacility AUTH
#################################
 ### TCPKeepAlive
 #################################
 # Specifies whether the system should send TCP keepalive messages
 # to the other side. If they are sent, death of the connection or
 # crash of one of the machines will be properly noticed. However,
 # this means that connections will die if the route is down tempo-
 # rarily, and some people find it annoying. On the other hand, if
 # TCP keepalives are not sent, sessions may hang indefinitely on
 # the server, leaving ``ghost'' users and consuming server
 # resources.
 # The default is ``yes'' (to send TCP keepalive messages), and the
 # server will notice if the network goes down or the client host
 # crashes. This avoids infinitely hanging sessions.
 # To disable TCP keepalive messages, the value should be set to
 # ``no''.
 # This option was formerly called KeepAlive.
 TCPKeepAlive no
#################################
 ### UseDNS
 #################################
 # Specifies whether sshd(8) should look up the remote host name and
 # check that the resolved host name for the remote IP address maps
 # back to the very same IP address. The default is ``yes''.
 UseDNS no
#################################
 ### UseLogin
 #################################
 # Specifies whether login(1) is used for interactive login ses-
 # sions. The default is ``no''. Note that login(1) is never used
 # for remote command execution. Note also, that if this is
 # enabled, X11Forwarding will be disabled because login(1) does not
 # know how to handle xauth(1) cookies. If UsePrivilegeSeparation
 # is specified, it will be disabled after authentication.
 # :: UseLogin is disabled to prevent the unlikely but unwanted use of an alternative login program. (This # :: isn't very useful. An intruder who can install an alternative login program probably can also edit
 # :: sshd_config to change this line.)
 UseLogin no
#################################
 ### UsePAM
 #################################
 # UsePAM Enables the Pluggable Authentication Module interface. If set to
 # ``yes'' this will enable PAM authentication using
 # ChallengeResponseAuthentication and PasswordAuthentication in
 # addition to PAM account and session module processing for all
 # authentication types.
 # Because PAM challenge-response authentication usually serves an
 # equivalent role to password authentication, you should disable
 # either PasswordAuthentication or ChallengeResponseAuthentication.
 # :: If key-only auth is used, disable PAM
 UsePAM no
#################################
 ### X11DisplayOffset
 #################################
 # Specifies the first display number available for sshd(8)'s X11
 # forwarding. This prevents sshd from interfering with real X11
 # servers. The default is 10.
 #################################
 ### X11Forwarding
 #################################
 # Specifies whether X11 forwarding is permitted. The argument must
 # be ``yes'' or ``no''. The default is ``no''.
 # When X11 forwarding is enabled, there may be additional exposure
 # to the server and to client displays if the sshd(8) proxy display
 # is configured to listen on the wildcard address (see
 # X11UseLocalhost below), though this is not the default. Addi-
 # tionally, the authentication spoofing and authentication data
 # verification and substitution occur on the client side. The
 # security risk of using X11 forwarding is that the client's X11
 # display server may be exposed to attack when the SSH client
 # requests forwarding (see the warnings for ForwardX11 in
 # ssh_config(5)). A system administrator may have a stance in
 # which they want to protect clients that may expose themselves to
 # attack by unwittingly requesting X11 forwarding, which can war-
 # rant a ``no'' setting.
 # Note that disabling X11 forwarding does not prevent users from
 # forwarding X11 traffic, as users can always install their own
 # forwarders. X11 forwarding is automatically disabled if UseLogin
 # is enabled.
 #################################
 ### X11UseLocalhost
 #################################
 # Specifies whether sshd(8) should bind the X11 forwarding server
 # to the loopback address or to the wildcard address. By default,
 # sshd binds the forwarding server to the loopback address and sets
 # the hostname part of the DISPLAY environment variable to
 # ``localhost''. This prevents remote hosts from connecting to the
 # proxy display. However, some older X11 clients may not function
 # with this configuration. X11UseLocalhost may be set to ``no'' to
 # specify that the forwarding server should be bound to the wild-
 # card address. The argument must be ``yes'' or ``no''. The
 # default is ``yes''.
 #################################
 ### XAuthLocation
 #################################
 # Specifies the full pathname of the xauth(1) program. The default
 # is /usr/bin/xauth.
#################################
 ### UsePrivilegeSeparation
 #################################
 # Splits up server processes in an attempt to prevent privilege escalation exploits.
 UsePrivilegeSeparation yes
#################################
 ### MaxAuthTries
 #################################
 # Maximum times a user can attempt to login per connection.
 # Failures are logged after half the number is reached.
 MaxAuthTries 6
#################################
 ### MaxStartups 10:30:60
 #################################
 # Specifies the maximum number of concurrent unauthenticated connections
 # to the SSH daemon (the number of users still logging in)
 MaxStartups 10:30:60
#
 ##
 ###
 ###################################################
 # Some other link(s) to be taken into consideration
 # http://ubuntuforums.org/showthread.php?t=831372
 ###################################################
 ###
 ##
 #
#################################
 ####### KEY CONFIGURATION #######
 #################################
 HostKey /etc/ssh/ssh_host_rsa_key
 HostKey /etc/ssh/ssh_host_dsa_key
 HostKey /etc/ssh/ssh_host_ecdsa_key
#################################
 ### PubkeyAuthentication
 #################################
 # Specifies whether public key authentication is allowed. The
 # default is ``yes''. Note that this option applies to protocol
 # version 2 only.
 PubkeyAuthentication yes
#################################
 ### AuthorizedKeysFile
 #################################
 # Specifies the file that contains the public keys that can be used
 # for user authentication. AuthorizedKeysFile may contain tokens
 # of the form %T which are substituted during connection setup.
 # The following tokens are defined: %% is replaced by a literal
 # '%', %h is replaced by the home directory of the user being
 # authenticated, and %u is replaced by the username of that user.
 # After expansion, AuthorizedKeysFile is taken to be an absolute
 # path or one relative to the user's home directory. The default
 # is ``.ssh/authorized_keys''.
 AuthorizedKeysFile %h/.ssh/authorized_keys

How to change SSH port in RunAbove VPS

OVH has launched a new VPS platform based on Docker and OpenStack, all powered by newly IBM’s POWER8 chips. This platform is called RunAbove(.com). You may give it a spin, they periodically offer coupons for tryouts.

Here’s an affiliate link which will load you with 10$: http://runabove.me/E9XH

Now onto our problem: you cannot change the SSH port in a fashion way, through /etc/ssh/sshd_config. You MUST first:

Login into your RunAbove account
Click on your name (upper right corner)
Select Expert Mode
Don’t lose your head into details, just go to Access & Security (on the left)
• Edit Rules for your default security group
• Add Rule (upper right corner)

  • Rule: Custom TCP
  • Direction: Ingress
  • Open Port: Port
  • Port: here you’ll input your desired nonstandard SSH port, >1024
  • Remote: select CIDR with 0.0.0.0/0 if you have 1 instance (VPS), otherwise go with Security Group: default (applies to all instances created under your account)

Now edit your sshd_config file and enter the port above into your config file. Reload service and enjoy.

PS: If you screw up the login and find yourself locked out of your box(es), from the Expert Panel check the Console tab (click on your instance’s name).

SOCKS5 Proxy directly from bash

Ever needed a SOCKS5 proxy on the go without the need of keeping Putty up and running? Here it is:

ssh -f -N -D 0.0.0.0:YOUR_DESIRED_PORT_ABOVE_1024 localhost
  • you will be prompted to enter your password
  • you can run this under any non-root account
  • you cannot control WHO you’re proxying so I’d better change this often

Anyways, I hope you’re running the SSH server on a non-default port:

ssh -p YOUR_SSHD_CONFIG_PORT -f -N -D 0.0.0.0:YOUR_PORT localhost

And if you’re using a FoxyProxy-like-program, make sure to check Perform remote DNS lookups on hostnames loading through this proxy.

 

You might want to consider: this link for using Putty | the method above beautifully explained.