note 86974 rejected from function.fopen by danbrown

From: Date: Thu, 13 Nov 2008 15:16:39 +0000
Subject: note 86974 rejected from function.fopen by danbrown
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-146492@lists.php.net to get a copy of this message
Note Submitter: andy at mail310 dot com ---- does anyone find it kind of retarded that generating a script that can read a file into a certain directory on the server will compromise your security? i mean just think about it this way... if you open a file in the directory /a/b/c/ depending on a GET or POST.... (REQUEST) so <?php if (isset($_REQUEST['file'])) { $filename = "a/b/c/".$_REQUEST['file']; $handle = fopen ($filename, "r"); echo fread($handle, filesize($filename)); fclose($handle); } ?> this script will now open ANY file on the server or account for that matter. how? it's real simple,let's say that the script above is contained into a file called read_files.php now we call the file like this... read_files.php?file=../../../index.php and that file will output exact code that is in the index.php file into the root directory for that website. Just imagine, this opens entirely your php code, as php will not be processed by the server, but given out as plain text. this means that you are basically showing your code and encryption mechanisms to anyone who wants to see them and knows where to look for it. I'm trying to figure out how to prevent this behavior, and so far the only thing seems to be making sure that the script excludes any files with an extension... ergo, you can not read or write to any file that contains a . on the server... or any path that contains a . for that matter... but if you need to be able to write in real time, say a php configuration file upon changing it's properties, you are pretty much not going to be able to do that without compromising your security. this is especially true, if like me you thought that specifying a directory and leaving only the file name up there, would make it so that just files in that directory can be red or written. I was surprised by not seeing any kind of security warning about this on this page. maybe it ought to be added, since fopen is what actually causes this behavior, which is a completely legit linux issue, in fact in liunx you can read any file on the server from any directory by adding a bunch of ../ in front of the path. can you block the path from containing ../ ? yes, you can, and i suggest you do too... <?php if (isset($_GET['file'])) { $filename = "a/b/c/".str_replace("../", "", $_GET['file']); $handle = fopen ($filename, "r"); echo fread($handle, filesize($filename)); fclose($handle); } ?> will delete any ../ in the string, making the script more solid, but I'm sure that it still could be circumvented, in some way i have yet to figure out.

« previous php.notes (#146492) next »