Σχόλια 0

Το κείμενο του εγγράφου

Published on The O'Reilly Network(http://www.oreillynet.com/)http://www.oreillynet.com/pub/a/php/2003/07/31/php_foundations.html

See thisif you're having trouble printing code examples

PHP Security, Part 1by John Coggeshall

07/31/2003In my last two columns (Common Style Mistakes, part oneand Common Style Mistakes, part two), Idiscussed some common bad practices to avoid when writing PHP scripts which can make them moredifficult to read and more prone to bugs. In today's column I'll change gears and discuss the meat of thisseries: the importance of security when working with PHP.The Importance of Thinking About SecurityMore than meets the eyeThe most effective and often overlooked measure to prevent malicious users from compromising yourscripts is to consider the possibility it could happen when you write them. It's s important to be mindfulof the possible security implications of your code.Consider the following example function designed to simplify the life of a developer who writes a greatmany text files from PHP scripts:<?phpfunction write_text($filename, $text="") {static $open_files = array();

// If filename is null, close all open filesif ($filename == NULL) {foreach($open_files as $fr) {fclose($fr);}return true;}$index = md5($filename);

if(!isset($open_files[$index])) {$open_files[$index] = fopen($filename, "a+");if(!$open_files[$index]) return false;}fputs($open_files[$index], $text);return true;}?>This function takes two parameters by default, the filename and the text to write to that file. Thefunction will first check to see if it has already opened that file in the past; if it has, it will reuse the oldPage1of4O'Reilly Network: PHP Security, Part 19/5/2003http://www.onlamp.com/lpt/a/4045file reference. Otherwise, it will create one if one doesn't exist. In either case, the text is then written tothe file. If the filename passed to the function is NULL, then all the opened file references are closed.An example usage is provided below.If the developer is writing a number of text files in this manner, this function will make his code lookmuch cleaner and easier to understand. Let's assume that this function lives in a separate file which isincluded in the scripts which require the function. Here's one of the scripts where it's used, calledquotes.php:<html><body><form action="<?=$_SERVER['PHP_SELF']?>" method="get">Choose the nature of the quote:<select name="quote" size="3"><option value="funny">Humorous quotes</option><option value="political">Political quotes</option><option value="love">Romantic Quotes</option></select><br />The quote: <input type="text" name="quote_text" size="30" /><input type="submit" value="Save Quote" /></form></body></html>

if (write_text($filename, $quote_msg)) {echo "<center><hr><h2>Quote saved!</h2></center>";} else {echo "<center><hr><h2>Error writing quote</h2></center>";}write_text(NULL);?>As you can see, this developer has used thewrite_text()function created previously to develop asystem to allow users to submit their favorite quotes, which are then saved to a text file. Unfortunately,though the developer may not know it, this script could also allow a malicious user to compromise thesecurity of the web server.Perhaps right now you are scratching your head and wondering exactly how such an innocent lookingscript poses such a security risk. Instead of asking you to figure it out yourself, consider the followingURL, remembering that the script itself is called quotes.php:http://www.somewhere.com/fun/quotes.php?quote=different_file.dat&quote_text=garbage+dataWhat will happen when this URL is presented to the web server? Obviously the quotes.php script willbe executed; but instead of writing a quote to one of the three desired files, a completely new file calleddifferent_file.dat will be written with a string garbage data inside of it. Obviously, this is not desiredbehavior at all. In fact, a malicious user might even be able to create an account by accessing the Unixpassword file by specifying ../../../etc/passwd for the quote parameter (although that would require theweb server to be running scripts as a superuser, and if that is the case you should stop reading this andfix that right now). Perhaps the most serious implication of this script is it could even be used to allowPage2of4O'Reilly Network: PHP Security, Part 19/5/2003http://www.onlamp.com/lpt/a/4045someone to write and execute arbitrary PHP scripts, if the /home/web/quotes/ directory were accessiblefrom a browser. The evil possibilities are endless.There are several solutions. If you only need to write a few files in the directory, consider using anassociative array to store the file names. If the user input exists in the associative array, it's safe to write.Another option is to strip out all non-alpha and non-numeric characters, to make sure there are nodirectory separators. Yet another idea is to check the file extension to make sure it won't be executed bythe web server.The bottom line is simple. As a developer you must be aware of morethan what your scripts do under the desired circumstances. What willhappen if invalid data is entered into a form element? Is there any way amalicious user could make your script behave in an unintended way?What measures are being taken to prevent these attacks? Your web serverand PHP scripts are only as safe as the weakest security link, so it'simportant to identify these possible weak links before they're identifiedfor you.Common security-related mistakesTo give you a few pointers, here's a brief and incomplete list of coding oradministrative failures which can compromise security:Mistake 1. Trusting dataAs will be the theme throughout my discussion of security as itrelates to PHP scripts, you should never trust data provided by anoutside source. No matter if it comes from a user-submitted form, afile in the filesystem, or an environment variable, nothing shouldsimply be taken at face value. All user input should be validatedand formatted to make sure it's safe.Mistake 2. Storing sensitive data in the web treeAny and all sensitive data should always be stored in a separate filefrom the script that needs it and stored in a directory that cannot beaccessed via a web server request. When the sensitive data inquestion is needed, that data can be included in the appropriate PHP script via an include orrequire statement.Mistake 3. Not implementing recommended security precautionsThe PHP manual contains an entire section devoted to security precautions when using and codingPHP scripts. The manual (almost) always clearly notes on a case-by-case basis when a potentialsecurity risk exists and how that risk can be minimized. Again, malicious users rely on developersand system administrators failing to pay attention to security concerns in order to gain access totheir systems. Heeding these warnings and acting appropriately significantly diminishes thechance of a malicious user being able to do any real damage to your system.More on security soonRelated Reading

Programming PHP

ByRasmusÂ

Lerdorf,KevinÂ

Tatroe

Table of Contents

Index

Sample Chapter

Read Online--Safari

Search this book on Safari:

Code Fragments onlyOnly This BookPage3of4O'Reilly Network: PHP Security, Part 19/5/2003http://www.onlamp.com/lpt/a/4045I cannot stress enough the importance of thinking about security in order to protect your servers frommalicious users. Now you should be looking at your scripts in a whole new light. With a littleexperience, soon you'll be catching these potential security lapses before you even write the code tocreate them. The next column will discuss a few more common ways security is compromised in PHPscripts and the steps you as a developer can do to minimize them.John Coggeshallis a a PHP consultant and author who started losing sleep over PHP around five yearsago.Read more PHP Foundationscolumns.Return to the PHP DevCenter.