User permissions for both apache and local user

I'm trying to allow permissions to files on the /home/user1/public_html/ folder for both user1 and for www-data (apache).

I've been instructed to run these commands:

sudo chown -R www-data:user1 /home/user1/public_html/
sudo chmod g+s /home/user1/public_html/

Now, www-data does have access to edit/remove/add files to /home/user1/public_html/ but user1 cannot edit anything.

How can I solve this?

Thanks,


Solution 1:

The best way to achieve this is with posix ACLs. Standard unix file permissions dont really cut it. You can do it with some kludging but its not really more than a kludge, basically its not a straight-forward solution.

Using a ACL will resolve this issue succintly. To do this you can use the following commands:

setfacl -R -m www-user:rwx /home/user1/public_html
setfacl -R -d -m www-user:rwx /home/user1/public_html
setfacl -R -m user1:rwx /home/user1/public_html
setfacl -R -d -m user1:rwx /home/user1/public_html

The -d flag causes new files to inherit the ACLs you set in the directory.

There are some caveats to bear in mind.

  1. Your filesystem must support it (most do these days, they can be enabled by remounting the filesystem with ACL support on most filesystems). Stuff like NFS wont work.
  2. The standard Unix group ACL becomes a mask. I.E if a file says g+x the file is executable with the command above. if its g-x the file is not executable, regardless of whether or not permissions set are rwx in the ACL. This ensures you avoid a situation where you would have to mark all directories rwx in the acl and all files rw-.

This fixes a problem sensibly and permits various combinations of scenarios:

  • It enforces least privilege as you are not required to start modifying group memberships of users.
  • user1 can create a file which can be modified later by www1-user (so user1 can SFTP upload content which could be deleted and/or modified by a CMS in apache later) and visa versa.
  • Apache remains in a system account which avoids having to use SetUID workarounds to change the apache subject (user).
  • The modification applies within a specific directory structure only and wont inadvertently permit www-user or user1 access to other portions of the file system tree you would not wish them to access.
  • Altering or revoking permissions is a trivial change.

This is my preferred way to resolve these kind of issues. It is a simple, non-disruptive and trivial change.

Solution 2:

Apache doesn't need to write everywhere, for this you can specify tmp,upload,etc. folders. So you can set permissions for public_dir to be readable and executable by apache user:

sudo chown user1:www-data /home/user1/public_html
sudo chmod 0750 /home/user1/public_html

All other files under public_html dir can be under user1 permissions and only readable by "others" (apache here). This is also better from security view. As I wrote, only necessary files/folder should be writable by apache user.