How do you permit PHP to write to a file without compromising server security

邮差的信 提交于 2019-12-01 20:01:02

问题


I am often confronted with negative comments whenever I want to have a PHP script write output to a file on the server.

I use the fopen(), fwrite() and fclose() functions.

The only way I know how to make this happen is to either set the permissions for the output file to 0666 or have it owned by "nobody" (which is the user that PHP runs under on our Apache web server).

So, if "0666" or "owned by nobody" are security risks, how do you successfully and securely allow a PHP script to write to a file?

Thanks for sharing guidance on this topic.


回答1:


If you need to access the files from PHP after they are uploaded then they need to be stored with permissions that let the web server (apache in this case) access them. The risk that people speak of is that some script on your site could be fooled into serving up the file. It is a hypothetical risk, but one that has occurred with many Content Management Systems. To mitigate this risk:

  1. Make the file name and path not easily guessable. If a user has a path to getfile.php?file=1.txt they can readily infer that there is a 2.txt as well. Crypt the name or make it unsequenced.
  2. Make any script that serves up files affirm things such as the logged in user, authorization to the resource and strip anything from the file name containing a path to avoid rogue references to /etc/passwd and the like.

If you just need to drop the file off and never serve it or access it via PHP again, you have some more options. Either use the chmod or chown commands to make it unreadable to the apache user. If you want to be extra paranoid, have a cron script move the file (and rename it) to a location unknown within the PHP source. At least then if your server is hacked the intruder can't walk right into the directory, but we are getting toward the point where the discussion veers into operating system security.




回答2:


The risk is if that writable directory resides in an area accessible to the outside world. Then those with the right tools and know how can write anything they want to that directory... or file. They can then place malware in it or create a phishing scheme on your site.

Really they can do all kinds of things to compromise you. I have seen this on my own servers and haven't really found the right solution to this.



来源:https://stackoverflow.com/questions/9261707/how-do-you-permit-php-to-write-to-a-file-without-compromising-server-security

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!