How to enable secure and convenient key-based SSH authentication (the easy and automagic way)

Recently I was up to the task of improving the SSH security on multiple servers. I was going to replace the less secure password based authentication with the more secure method of using SSH keys, which also has the added benefit of being more convenient as I do not have to type my password each time I login to the servers.

And being a really big fan of automation, and especially to avoid reproducing boring and repetitive tasks, I thought I might find and smarter and easier way than remembering all those steps needed for each machine. So I decided to write an automagic AllowSSH bash script for this. This way I could perform the task easily and more reliably on multiple hosts (and it will be far easier to remember in the future). This is how the script is used:

$ ./AllowSSH root@192.168.100.100

Before running the script you need to make sure you have a SSH RSA key generated and that you are logged in as the user you want to grant access to the remote machine. Se details below with an description of what the script actually does.

The easiest way to install the AllowSSH-script to your local computer is running the following command:

$ curl -L http://bit.ly/install-allowssh | bash

The above install script will download the AllowSSH.sh script to the current folder and making it executable. Then the script is ready to be executed using the “AllowSSH [{username}@]host” syntax. And remember to run the script as the user you want to grant access to the remote machine.

Prerequisites

  • Login as the user you want grant access to the remote machine
  • Generate a SSH RSA key using $ ssh-keygen -t rsa
  • Have a user ready for SSH on the remote machine with enough privileges to add a new user and change that user’s home folder (typically root or a sudo-account)

What the script does

Basically the script performs these actions (somewhat simplified):

  1. Reads your SSH key
  2. Logins (SSH) to the remote server using the [{username}@]host parameter supplied to the script
  3. Creates a new user using your current username (logged-in user)
  4. Creates the /home/{user}/.ssh/ folder
  5. Adds your RSA key to the ‘authorized_keys
  6. Sets required permissions

 

 

Advertisements

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s