Share via:

Permissions with SSH and SFTP

How to have files uploaded through SFTP correctly inherit the group permissions of the parent directory.


Edited: 2019-12-19 12:22

When either creating new files through SSH, or uploading files through SFTP with a client such as FileZilla, WinSCP, and CyberDuck you may run into a problem where the files have the wrong group ownership and/or permissions assigned after uploading, rendering them inaccessible to your web-server.

It often happens because of incorrect access rights in directories. The problem with ownership can be solved with setgid or setuid.

When you want a web-server to access the files, you would usually want the files to be assigned a certain group. Depending on your configuration, this will either be the users group, or a shared web-server group, such as www-data for Apache.

In order to fix it, we can set the setgid flag on the directory shared with the web-server.

Note. Often this directory will be /var/www/

Doing this will make files uploaded through SFTP "inherit" the group ownership from the parent directory. To do this recursively, we can use this command:

find /var/www/ -type d -exec chmod g+s {} +

The above will target only directories (-type d) using the find command. As for the chmod, the g represents setgid, while the +s enables it. To disable it again, simply run the command with -s instead.

About setgid and setuid

By default, a process will be run as the user who started it. When we, in this case, set the setgid bit of a directory, the process will instead run with the access rights of the group that owns the files.

It is a way to "force" files and directories to have the desired group ownership when uploaded, and indeed, even when created by the web-server itself.

If we instead want to run a process with the access rights of the user, we can set the setuid flag on the directory. To do this, we simply use u instead of g:

find /var/www/ -type d -exec chmod u+s {} +