What is the best Linux user / permission setting for a folder that PHP can write to?

After years of using chmod 777 to solve PHP resolution problems, I want to know the correct way to solve the problem.

I have a site on my server belonging to user1 in group user1 . There is a uploads folder on this website.

Usually, to write with PHP, I have to chmod set this folder to 777 . But I obviously admit that this is dangerous and wrong, and I want to set permissions correctly to minimize the risk.

From my limited knowledge, I see two options:

  • I chown uploads folder so that it belongs to apache . That way, I can just use the default permissions, and apache can happily write to a folder.
  • I am adding a second group to apache from user1 . Then I give write permission to the owner and group on uploads , what should allow apache to write to uploads ?

My question is: what's the best approach? Is this one of the above or something completely different?

If the best solution is # 1, how can user1 also write to download via SFTP, since this solution will not allow them?

+4
source share
2 answers

In my current company, we installed the apache group in the group that owns the folder, so you just need to make chmod 770 in the folder to give this particular group permission to do funny things in this folder.

However, you still should not protect your application from a malicious user, since a running PHP script, if it is insecure enough, can still damage the folder.

+1
source

If this is your own server, the best way is to set the folder in the group used by apache, for example. from chgrp www-data to debian (may vary on other systems). You should usually do this as root, or at least as a user who has access to his own and www data group. If your user has access to the www-data group, this can be a great opportunity for you, as it is easy to read and possibly write / move files. In this case, use 770 as the file permission and make sure the files created by php get this permission (either explicitly after creating with chmod, or using umask before creating. See the php manual for both.)

If you work in a shared hosting environment, the only clean solution I know is mod_suexec , but I don’t know many hosts that support it. If this is not available, I only know what you know when working with 777. Often your home directory in shared environments has a longer random string in the path name so that others cannot find your directory and therefore cannot access your files. But this is not real security ..; -)

Good luck Michelle

+1
source

All Articles