PDA

View Full Version : A safe way to write files in PHP


Roger
3rd January 2008, 22:29
In order for PHP to write files to the server using fwrite or related filesystem functions, the relevant directory has to be enabled for writing, ie permissions set to 777, which is a security exposure and Othello systems were compromised by hackers exploiting this loophole. I used to have directories with permissions at 777 (and some of my sites were hit) but not AFAIK any longer.

This has caused me problems in that I had to write cgi PERL routines to update files, which is more secure but a pain due to the terse nature of PERL error messages. Now I have a PHP method which, under the appropriate conditions, seems to be safe. Here it is:

The trick is to use the PHP FTP functions, see http://uk3.php.net/ftp , and crucially to only let trusted logged-in users have access to them. This is what I did, I can provide more details if anybody wants them:
I used cPanel to define an FTP user able to upload to the relevant directory (and not to the whole site). If more people needed access, I would define more FTP users.
I have a system that authenticates users via a mySQL database that holds the passwords as an MD5 hash so the password isn't held in clear. However, the same password is used as for the FTP user, and the password is held as a session variable for the duration of the session.
The HTML code has a form which uploads the file, Apache puts it in a temporary file. Conventional coding would then copy it to a permanent location using filesystem functions, for example move_uploaded_file().
Instead I use, in sequence the commands
ftp_connect
ftp_login
ftp_put
ftp_close
The other FTP commands e.g. ftp_delete are also available once logged in.Obviously other security considerations apply: you need to check that the files being uploaded are what they purport to be and that they are benign; you need to ensure that the users you give this to are trustworthy. But because it is not open to all, and is password-protected, I believe it's a useful way of uploading files.

The first implementation has been in a CMS to allow the customer to upload images and PDFs.

Any comments?

Roger