Security Considerations


Hopefully you have realized that having on your web server a script that is able to execute host program commands is not always a good idea. In fact, in Lesson 24, "PHP Security," you will learn how you can use PHP's Safe Mode to place restrictions on host program execution.

To end this lesson, you will learn how to make sure that host program execution is always done safely.

Escaping Shell Commands

Consider the script in Listing 18.2, which creates a web form interface to the finger command.

Listing 18.2. Calling the finger Command from a Web Form
 <FORM ACTION="finger.php" METHOD="POST"> <INPUT NAME="username" SIZE=10> <INPUT TYPE="SUBMIT" VALUE="Finger username"> </FORM> <?php if ($_POST["username"]) {   $cmd = "finger {$_POST['username']}";   echo "<PRE>" . `$cmd` . "</PRE>"; } ?>  

If you run this script in your browser and enter a username, the finger information will be displayed.

However, if you instead enter a semicolon followed by another commandfor instance, ;lsthe finger command is run without an argument and then the second command you entered is executed. Similar trickery can be produced using other symbols, depending on your web server platform.

This is clearly not a good thing. You might think that only limited damage could be done through running processes as the same user as the web server; however, many serious exploits can take advantage of this behavior. A malicious user could issue a command such as wget or lynx to install a hostile program on your server's hard disk and then run it. This could be a rootkit to attempt to take advantage of other server vulnerabilities, or it could be a script to launch a denial-of-service attack by eating up all your system resources. However you look at it, giving anonymous users this kind of access to your web server is bad news.

To protect yourself against this kind of attack, you should use the escapeshellcmd function. Any characters that may be used to fool the shell into executing a command other than the one intended are prefixed with a backslash. This way, undesirable characters actually become arguments to the command.

To make Listing 18.2 safe, the statement that builds $cmd should be changed to the following:

 $cmd = escapeshellcmd("finger {$_POST['username']}"); 

Now, entering ;ls into the form will result in the command executed being finger \; lsactually attempting to find users called ; or ls on your system.



    Sams Teach Yourself PHP in 10 Minutes
    Sams Teach Yourself PHP in 10 Minutes
    ISBN: 0672327627
    EAN: 2147483647
    Year: 2005
    Pages: 151
    Authors: Chris Newman

    Similar book on Amazon

    flylib.com © 2008-2017.
    If you may any questions please contact us: flylib@qtcs.net