Limit SSH key to SCP only

After you copy your keyfile to the server:

ssh-copy-id -i ~/.ssh/id_rsa_for_scp [email protected]

(To simplify the example, we will assume the client's machine ~/.ssh/config is already configured. For more details about ~/.ssh/config run man ssh_config)

Host testmachine
    Hostname 192.168.1.1
    User legendaryuser
    BatchMode yes
    IdentitiesOnly yes
    IdentityFile ~/.ssh/id_rsa_for_scp

You will need to edit the server's /home/legendaryuser/.ssh/authorized_keys file.

From:

ssh-rsa AAAAAC3nZCXExxHUEBR...

To: (this version allows download and upload)

command="if [[ \"$SSH_ORIGINAL_COMMAND\" =~ ^scp.? ]]; then $SSH_ORIGINAL_COMMAND ; else echo Access Denied; fi" ssh-rsa AAAAAC3nZCXExxHUEBR...

If you want to limit scp to "download-only mode" and only to files from a specific directory, do:

command="if [[ \"$SSH_ORIGINAL_COMMAND\" =~ ^scp[[:space:]]-f[[:space:]]/full/path/to/dir/.? ]]; then $SSH_ORIGINAL_COMMAND ; else echo Access Denied; fi" ssh-rsa AAAAAC3nZCXExxHUEBR...

And last, lets add some more restrictions to the key, just to be safe:

command="if [[ \"$SSH_ORIGINAL_COMMAND\" =~ ^scp[[:space:]]-f[[:space:]]/full/path/to/dir/.? ]]; then $SSH_ORIGINAL_COMMAND ; else echo ERRO Access Denied; fi",no-pty,no-port-forwarding,no-agent-forwarding,no-X11-forwarding ssh-rsa AAAAAC3nZCXExxHUEBR...

You can see more details about the authorized_keys file by running:

man sshd

Ps: You can also add from=xxx.xxx.xxx.xxx to the limit the use of the key from a specific IP address or network.

Pps: Sorry for my english, I'm not a native speaker.


Supplement to @Michael Richard's answer.

zsh will return an error:

zsh:1: no such file or directory: scp ...

This problem also exist in bash.

To solve it, replace

... then $SSH_ORIGINAL_COMMAND ; ...

to

... then $SHELL -c $SSH_ORIGINAL_COMMAND ; ...