keychain: Set Up Secure Passwordless SSH Access For Backup Scripts

by on June 6, 2009 · 11 comments· LAST UPDATED June 17, 2009

in , ,

We establish connections to remote systems without supplying a password, however I do not want to store my password less keys ( passphrase-free keys) on my servers. ssh-agent, takes care of keys with passphase, which allowing me to easily have ssh-agent process per system per login session. How do I dramatically reduces the number of times I've to punch my passphrase from once per new login session to once every time my local server is rebooted? How do I use keychain utility for all my backup scripts for secure passwordless login?

OpenSSH offers RSA and DSA authentication to remote systems without supplying a password. keychain is a special bash script designed to make key-based authentication incredibly convenient and flexible. It offers various security benefits over passphrase-free keys.

How Does Keychain Make It Better Than a Key Less Passphrase?

If attacker broken into server with passphrase-free keys, all other your servers / workstation on which keys are used are also security risk (they can be easily breached). With keychain or ssh-agent attacker won't able to touch your remote systems without breaking your passphrase. Another example, if your laptop or harddisk stolen, an attacker can simply copy your key and use it anywhere as it is not protected by a passphrase.

keychain is a manager for ssh-agent, typically run from ~/.bash_profile. It allows your shells and cron jobs to share a single ssh-agent process. By default, the ssh-agent started by keychain is long-running and will continue to run, even after you have logged out from the system. If you want to change this behavior, take a look at the --clear and --timeout options, described below. Our sample setup is as follows:

peerbox.nixcraft.net.in => Remote Backup Server. Works in pull only mode. It will backup server1.nixcraft.net.in and server2.nixcraft.net.in.
vivek-desktop.nixcraft.net.in => My desktop computer.
server1.nixcraft.net.in => General purpose remote server.
server2.nixcraft.net.in => General purpose remote web / mail / proxy server.

Install keychain software on peerbox.nixcraft.net.in so that it can login securely to other two servers for backup.

Install keychain on CentOS / RHEL / Fedora Linux

You need RPMForge repo enabled to install keychain package.
# yum install keychain

Install keychain on Debian / Ubuntu Linux

# apt-get update && apt-get install keychain

Install keychain on FreeBSD

# portsnap fetch update
# cd /usr/ports/security/keychain
# make install clean

How Do I Setup SSH Keys With passphrase?

Simply type the following commands:
$ ssh-keygen -t rsa
OR
$ ssh-keygen -t dsa
Assign the pass phrase when prompted. See the following step-by-step guide for detailed information:

  1. Howto Linux / UNIX setup SSH with DSA public key authentication (password less login)
  2. Howto use multiple SSH keys for password less login

How Do I Use Keychain?

Once OpenSSH keys are configured with a pass phrase, update your $HOME/.bash_profile file which is your personal initialization file, executed for login BASH shells:
$ vi $HOME/.bash_profile
Append the following code:

### START-Keychain ###
# Let  re-use ssh-agent and/or gpg-agent between logins
/usr/bin/keychain $HOME/.ssh/id_dsa
source $HOME/.keychain/$HOSTNAME-sh
### End-Keychain ###

Now you've keychanin configured to call keychain tool every login. Just log out and log back in to server from your desktop to test your setup:
$ ssh root@www03.nixcraft.net.in
Sample Output:

Fig.01 - Keychain in Action

Fig.01 - Keychain in Action

keyhcain is up and running. Now, all you have to do is append your servers key file $HOME/.ssh/id_dsa.pub to other UNIX / Linux / BSD boxes:
# scp $HOME/.ssh/id_dsa.pub server1.nixcraft.net.in:~/pubkey
# scp $HOME/.ssh/id_dsa.pub server2.nixcraft.net.in:~/pubkey
# ssh server1.nixcraft.net.in cat ~/pubkey >> ~/.ssh/authorized_keys2; rm ~/pubkey
# ssh server2.nixcraft.net.in cat ~/pubkey >> ~/.ssh/authorized_keys2; rm ~/pubkey
# ssh root@server1.nixcraft.net.in
# ssh user@server2.nixcraft.net.in

Task: Clear / Delete All Of Ssh-agent's Key

# keychain --clear

Security Task: Make Sure Intruder Cannot Use Your Existing SSH-Agent's Keys (only allow cron jobs to use password less login)

The idea is pretty simply only allow backup shell scripts and other cron job to do password less login but all users including an intruder must provide a passphrase-key for interactive login. This is done by deleting all of ssh-agent's keys. This option will increases security, it still allows your cron jobs to use your ssh keys when you're logged out. Update your ~/.bash_profile as follows:

/usr/bin/keychain --clear $HOME/.ssh/id_dsa

If you are using RSA, use:

/usr/bin/keychain --clear $HOME/.ssh/id_rsa

Now, just log in to remote server box once :
$ ssh root@peerbox.nixcraft.net.in
Log out (only grant access to cron jobs such as backup)
# logout

Task: Use Keychain With Backup Scripts for Passwordless login via cron

Add the following before your rsync, tar over ssh or any other network backup command:

source $HOME/.keychain/$HOSTNAME-sh

Here is a sample rsync script:

#!/bin/bash
# Remote Server Rsync backup Replication Shell Script
# Local dir location
LOCALBAKPOINT=/iscsi
LOCALBAKDIR=/backups/server1.nixcraft.net.in/wwwroot
# Remote ssh server setup
SSHUER=root
SSHSERVER=server1.nixcraft.net.in
SSHBACKUPROOT=/wwwroot
 
# Make sure you can log in to remote server without a password
source $HOME/.keychain/$HOSTNAME-sh
 
# Make sure local backup dir exists
[ ! -d ${LOCALBAKPOINT}${LOCALBAKDIR} ] && mkdir -p ${LOCALBAKPOINT}${LOCALBAKDIR}
 
# Start backup
/usr/bin/rsync --exclude '*access.log*' --exclude '*error.log*' -avz -e 'ssh ' ${SSHUER}@${SSHSERVER}:${SSHBACKUPROOT} ${LOCALBAKPOINT}${LOCALBAKDIR}
 
# See if backup failed or not to /var/log/messages file
[ $? -eq 0 ] && logger 'RSYNC BACKUP : Done' || logger 'RSYNC BACKUP : FAILED!'

If you are using rsnaphot backup server (see how to setup RHEL / CentOS / Debian rsnapshot backup server) add the following to your /etc/rsnapshot.conf file

# Get ssh login info via keychain
cmd_preexec    source /root/.keychain/hostname.example.com-sh

Final Note About Keychain and Security

  • Cracker with an advanced attacking with deadly coding skills can still get key from memory. However, keychain makes it pretty difficult for normal users and attackers to steal your keys and use it.
  • OpenSSH sshd server offers two additional options to protect abuse of keys. First, make sure root login disabled (PermitRootLogin yes). Second, specify which user accounts on the server are allowed to be used for authentication by adding AuthorizedKeysFile %h/.ssh/authorized_keys_FileName. See sshd_config man page for further details.

Suggested Readings:

TwitterFacebookGoogle+PDF versionFound an error/typo on this page? Help us!

{ 11 comments… read them below or add one }

1 Colin June 6, 2009 at 10:20 pm

I think I found a typo.
“OpenSSH sshd server offers two additional option to protect abuse of keys. First, make sure root login disabled (PermitRootLogin yes).”

Reply

2 Ulver June 8, 2009 at 1:11 pm

another interesting way to protect ssh, is chroot them, but it depends of the particulary needs of each one

Reply

3 Lexsys June 19, 2009 at 8:11 am

I have a problem with my rsnapshot configuration. If I enter your command into rsnapshot.conf file, I get an error:
ERROR: cmd_preexec source /home/lexsys/.keychain/dev-server-sh - "source" is not executable or can't be found. Please use an absolute path.

I created an executable 1.sh, placed the command into this file and write in rsnapshot.conf:
cmd_preexec /root/1.sh

Everything works fine.

Reply

4 Heikki Orsila July 26, 2009 at 4:47 pm

ssh-copy-id command is an easier way to copy your public key to a server:

ssh-copy-id -i ~/.ssh/id_dsa.pub user@host

Reply

5 Neil Jensen September 30, 2009 at 4:43 am

Hi, I have been trying to get rsnapshot to run with keychain under cron for root when logged out.

For me adding
source /root/.keychain/-sh
to cmd_preexec in the rsnapshot.conf did not work
What has finally worked for me which works remotely and locally is:
under cron run a command pointing to shell scripts for hourly daily weekly and monthly rsnapshots

my script is for hourly backups is hourly.sh
#!/bin/bash
ENV=/root/.bashrc
source /root/.keychain/-sh
rsnapshot hourly

the reason why this was needed is because cron for ssh doesn’t enter a shell to perform it’s function, so before rsnapshot begins you must point the process into a shell or you get an annoying and failing error 255 stating rsync couldn’t ssh(or something like that). Then just re comment the cmd_preexec line in the rsnapshot.conf

Reply

6 nigg belamps October 15, 2010 at 2:06 pm

hahaha root@pee … thats hot

Reply

7 Philip Hands October 19, 2010 at 5:22 am

An alternative approach is to lock down passphraseless keys so they do exactly and only what they need, so that an attacker doesn’t actually get anything useful even if they do manage to steal the key.

The thing about needing to be an uber-hacker to get at the keys in memory is a resort to security through obscurity, which will encourage sloppy thinking about the real issue, which is that you in effect have passwordless keys on the system, so you should make sure that those keys only get to do what you want and nothing more. As shown in the above link, it’s possible to lock it down to the point that the keys only open up the tiny crack of read-only access from the right IP address, so an attacker really gets nothing from having such keys. I seriously doubt anyone using this keychain approach will bother with the command= bit in their authorised_keys file, which means that they’re giving an attacker much more if there is a break-in.

Oh, and you should be setting PermitRootLogin to without-password, or no (rather than yes)

Reply

8 Halil January 14, 2011 at 8:25 pm

I still receive :
Error:Permission denied, please try again.
Permission denied, please try again.
Permission denied (publickey,password).
rsync: connection unexpectedly closed (0 bytes received so far) [sender]
rsync error: unexplained error (code 255) at io.c(454) [sender=2.6.9]

Reply

9 milan February 11, 2011 at 5:43 am

Hi

good post .i was wondering,what if i lost password in this case.

Reply

10 Bigby Findrake August 23, 2012 at 10:59 pm

> With keychain or ssh-agent attacker won’t able to touch your remote
> systems without breaking your passphrase.

This is not true; this is false (at least in the case of ssh-agent): If I have file level access to the ssh-agent socket on a host where you are running ssh-agent, I can use (but not save) all of the keys that have been loaded into ssh-agent (unless you are locking the ssh-agent, which you say nothing about and which would defeat the nature of automated authentication).

Reply

11 akaul June 20, 2013 at 4:52 am

Nice Article.. !!

Reply

Leave a Comment

Tagged as: , , , , , , , , , , ,

Previous Faq:

Next Faq: