Setting default permissions on files and directories copied with scp or sftp

I've found many questions on the net regarding the topic so it's time I give you my own answer. Smile In case of SFTP you're lucky: you've at least two methods to do it ...

  1. You can rename the sftp-server binary to something else and create a wrapper shell script that will set the umask and call the real sftp-server. Something like this should do:
    mv /usr/lib/sftp-server /usr/lib/sftp-server.orig
    cat <<EOF
    #!/bin/sh
    umask 002
    /usr/lib/sftp-server.orig "$@"
    EOF
    chmod a+x /usr/lib/sftp-server
  2. You can use the libpam-umask PAM module to set the umask.
In case of SCP you're not so lucky. There're many speculations on the net about how to force SCP to create files an directories with a specific umask. However once you take a quick look at the source code of SCP, you find it out: it tries to copy the permissions of the source to the target, so the permissions of the files created on the server depend on the permissions of the original files on the client. SCP explicitly sets the file and directory permissions on the server and there's no way around it (of course assuming you do not alter SCP's source and compile it yourself).

If you have to control permissions of uploaded files and directories, I see two options:
  1. Restrict file upload to SFTP only. A simple way to do so is to revoke execute permission from "others" on SCP (eg. chmod o= /usr/bin/scp). Of course this will not only limit the upload via SCP to the server, but it'll prohibit use of scp for local users on the server too (unless the user has his own copy of scp or compiles one from source). The sshd looks for scp in the system default PATH, so it's not enough either to just move the scp binary to a different location (eg. /usr/local/bin), because sshd will find it there too if it's on the PATH.
  2. The other option is to have a cron job that periodically resets the permissions on the uploaded files and directories. This is something of a mess, but many eventually choose this option.