DEV Community

Cover image for Add non-sudoer user with ssh access to a specific directory
Jaeyson Anthony Y.
Jaeyson Anthony Y.

Posted on

Add non-sudoer user with ssh access to a specific directory

Suppose you want to add another public key (id_rsa.pub) on an existing non-sudoer user, e.g. ftpuser for your teammate or another machine that you'll sshing often and you want this user to have access to a specific dir. In this example we'll use /var/www/html as the specific dir, also I'm using ubuntu as an example server.

1. (optional) where's the home dir of userA?

If for some odd reason your non-sudoer user has a different home directory like /var/www/html, you may want to move it back to its default dir and symlinking it instead:

# server
sudo usermod -m -d /home/userA userA
Enter fullscreen mode Exit fullscreen mode

2. create .ssh dir and authorized_keys file if not exists

# server
mkdir /home/userA/.ssh && chmod 700 $_
touch authorized_keys && chmod 600 $_
Enter fullscreen mode Exit fullscreen mode

3. symlink a directory (e.g. /var/www/html)

# server
# ln -s /var/www/html /home/userA/link_name
ln -s /var/www/html /home/userA/www
Enter fullscreen mode Exit fullscreen mode

4. authorized_keys file in /etc/ssh/sshd_config

This is where we read keys that are authorized to log in:

# server
# add/update this line accordingly
AuthorizedKeysFile /home/old_user/.ssh/authorized_keys  /home/userA/.ssh/authorized_keys
Enter fullscreen mode Exit fullscreen mode

then restart it with sudo service sshd restart

5. add client's public key (id_rsa file) to server:

let's check if we have keys:

# client
# check if there's any keys exists
ls -al ~/.ssh

# otherwise create one
# for the rsa file you could
# name it like userA_id_rsa
ssh-keygen -t rsa -b 4096 -C "your comment"

# start in background
eval "$(ssh-agent -s)"

# adds key to ssh-agent, it'll ask for passphrase
ssh-add ~/.ssh/userA_id_rsa

# copy public key to authorized_keys in server
cat ~/.ssh/userA_id_rsa | ssh sudouser@host.domain -vvv "cat - >> /home/userA/.ssh/authorized_keys"

# or if the sudo user uses key for loggin in
cat ~/.ssh/userA_id_rsa | ssh sudouser@host.domain -vvv -i ~/.ssh/sudouser_id_rsa "cat - >> /home/userA/.ssh/authorized_keys"
Enter fullscreen mode Exit fullscreen mode

6. then log in:

userA@host.domain -vvv -i ~/.ssh/userA_id_rsa

# remember step 3 symlink?
# once logged in successfully, confirm if
# you can see /var/www/html in your home dir:
# ls -la ~/home/userA/link_name
ls -la ~/home/userA/www
Enter fullscreen mode Exit fullscreen mode

saving ssh config

have some ssh config handy (~/.ssh/config):

Host userA.domain
  HostName host.domain
  User userA
  PreferredAuthentications publickey
  IdentityFile ~/.ssh/userA_id_rsa
  IdentitiesOnly yes
  RemoteForward 52698 localhost: 52698
Enter fullscreen mode Exit fullscreen mode

then log in ssh userA.domain -vvv

Discussion (0)