Importing a Public SSH Key

Rex was setting up a server and wanted some help.  His hosting provider had set him up with a username and password for authentication. He wanted me to log in to the machine under his account to help out.  I didn’t want him to have to give me his password.  Rex is a smart guy, but he is not a Linux user.  He is certainly not a system administrator.  The system was CentOS.  The process was far more difficult to walk


CORRECTION: I had the keys swapped. It is important to keep the private key private, and that is the one in $HOME/.ssh/id_rsa

I use public keys cryptography all the time to log in to remote systems.  The OpenSSH client uses a keypair that is stored on my laptop under $HOME/.ssh.  The public key is in $HOME/.ssh/id_rsa.pub and the private one is in $HOME/.ssh/id_rsa.  In order for the ssh command to use this keypair to authenticate me when I try to login, the key stored in $HOME/.ssh/id_rsa.pub first needs to be copied, to the remote machine’s $HOME/.ssh/authorized_keys file.  If the permissions on this file are wrong, or the permissions on the directory  $HOME/.ssh are wrong, ssh will refuse my authentication attempt.

Trying to work this out over chat with someone unfamiliar with the process was frustrating.

This is what the final product looks like.

rex@drmcs [~]# ls -la $HOME/.ssh/
total 12
drwx------ 2 rex rex 4096 Sep 21 13:01 ./
drwx------ 9 rex rex 4096 Sep 21 13:28 ../
-rw------- 1 rex rex  421 Sep 21 13:01 authorized_keys

This should be scriptable.

#!/bin/bash
SSH_DIR=$HOME/.ssh/
AUTHN_FILE=$SSH_DIR/authorized_keys

SSH_KEY="PASTE PUBLIC KEY HERE, ALL ON ONE LINE, THEN REMOVE THE NEXT LINE"
exit 0

mkdir -p $SSH_DIR
chmod 700 $SSH_DIR
touch $AUTHN_FILE
chmod 600 $AUTHN_FILE
echo $SSH_KEY >> $AUTHN_FILE

However, it occured to me that he really should not even be adding me to his account, but, instead, should be creating a separate account for me, only giving me access to that, which would let me look around but not touch. Second attempt:

#!/bin/bash

NEW_USER="NEW USERNAME"
SSH_KEY="PASTE PUBLIC KEY HERE, ALL ON ONE LINE, THEN REMOVE THE NEXT LINE"
exit 0

/usr/sbin/useradd $NEW_USER
SSH_DIR=/home/$NEW_USER/.ssh/
AUTHN_FILE=$SSH_DIR/authorized_keys

mkdir -p $SSH_DIR
chmod 700 $SSH_DIR
touch $AUTHN_FILE 
chmod 600 $AUTHN_FILE
echo $SSH_KEY >> $AUTHN_FILE 

chown -R $NEW_USER:$NEW_USER $SSH_DIR

To clean up the account when I am done, Rex can run:

sudo /usr/sbin/userdel -r admiyo

Which will not only remove my account, but also the directory /home/ayoung
If I have left a login he will see:

userdel: user admiyo is currently used by process 3561

2 thoughts on “Importing a Public SSH Key

  1. check this Adam,

    The public key is in $HOME/.ssh/id_rsa and the private one is in $HOME/.ssh/id_rsa.pub.

Leave a Reply

Your email address will not be published. Required fields are marked *