ssh - generating keys

 

I need an automated program on machine "seq" to rsync to machine "four" as user "miseq".  To maintain security, I only want to allow this automated process to run rsync - nothing else.

Steps:

  1. On "seq", run 

    ssh-keygen -t rsa

    enter NO passphrase - just hit return both times.  Do NOT use "id_rsa" as the name of the private key file - name it something like "id_rsa.seq2four".  Note that this also creates the file id_rsa.pub - you will need the line inside this file for the next step on "four".

  2. On "four", create or append to the file ~.ssh/authorized_keys the single line key that was in id_rsa.pub on "seq" generated in step 1, or use "ssh-copy-id -i id_rsa.seq2four <user>@<four>.

  3. Create an executable shell script on "four" that contains this simple script - let's call it "~/bin/validate-rsync-ssh.sh":

  1. #!/bin/bash
    case "$SSH_ORIGINAL_COMMAND" in
    	rsync\ --server*)
    		# uncomment for debug
    		# echo "$(date +%Y%m%d): $SSH_ORIGINAL_COMMAND" >> /var/log/ssh-cmd.log
    		$SSH_ORIGINAL_COMMAND
    		;;
    	# debug
    	testconnect)
    		echo "You successfully connected to $(hostname)"
    		;;
    	*)
    		echo "Sorry, command '$SSH_ORIGINAL_COMMAND' is not allowed"
    		exit 1
    		;;
    esac

    Don't forget to make this file executable (chmod +x validate-rsync-ssh.sh).

  2. Pre-pend the text: command="~/bin/validate-rsync-ssh.sh" to your ssh-rsa key in the file ~/.ssh/authorized_keys, with a space between this and the text "ssh-rsa".
  3. Now test everything by doing this command back on "seq":

    ssh -i ~/.ssh/id_rsa.seq2four miq@four testconnect

    This should give you the message from your "validate-rsync-ssh.sh" script, "You successfully connected to four".  Commands other than "testconnect" should give you the, "Sorry, command... is not allowed" error message.

  4. Now try your rsync from "seq" to "four" - it should work smoothly:

    rsync -avP -e 'ssh -i /home/me/.ssh/id_rsa.seq2four' localfiles.txt miq@four:RemoteDir

    Note that the path to your "id_rsa.seq2four" must be absolute - the shell and rsync get confused about who's expanding what when if you try using variables or "~".


    Other notes:

    ssh is VERY picky about the permissions of the .ssh directory on "four" - they MUST be:

     

    miseq@four:~/.ssh$ ls -la
    drwx------  2 miq group 4096 2013-07-25 10:36 .

    IN ADDITION - the .ssh directory should be tight:

    chmod 700 ~/.ssh
    ls -ld .ssh:
    drwx------ 2 miq group 4096 Nov 26 17:25 .ssh

    AND your home dir must be at least 775:

  5. chmod 775 ~
    ls -ld ~
    drwxrwsr-x 22 miq group 4096 Nov 26 17:25 /home/miq