Page 1 of 1

PHP Security Crash Course Start protecting your apps today with this primer Rate Topic: ***** 1 Votes

#1 joeyadms   User is offline

  • D.I.C Head
  • member icon

Reputation: 41
  • View blog
  • Posts: 178
  • Joined: 04-May 08

Post icon  Posted 17 May 2008 - 01:47 PM

PHP is a great language, and many people use it as their first programming language. The problem is that just as lower level programmers have their vulnerabilities, we also have ours, that are all too common in production websites today. Here I will try to address some of the more popular topics.

Keep in mind I go over the basics of each attack. Each attack can cover an entire paper by itself.

1. SQL Injection

SQL Injection occurs when programmers use variable data in SQL statements without escaping the data first. Lets take a look at this query for a login script.
$username = $_POST['username'];
$password = $_POST['password'];
$query = "SELECT * FROM `users` WHERE `username` = '$username" AND `password` = '$password';

Our programmer has made a grave mistake. He has not filtered or escaped the post data before using it in a query. Why is that so important? Lets have a look at what happens when an attacker messes with this script.

Lets see what the query will look like when the attacker enters a username of admin and a password of ' or 1=1--

$query = "SELECT * FROM `users` WHERE `username` = 'admin' AND `password` = '' or 1=1--

Oh my. By looking at the query you can see that MYSQL will return any row that has a username of admin and a password of '' or if 1=1. Since 1=1 always, every row with username admin will be returned and our attacker will be authenticated as 'admin'.

If the user implements the ' or 1=1-- in the username field, he will be authenticated as the first row of the database.

Now picture if the attacker enters other harmful statements like DROP. Or in other serious instances, like on MSSQL servers, stored procedures such as xp_cmdshell will give the attacker remote command execution on your SQL server.

To mitigate these attacks ALWAYS escape ANY variable data used in queries. For example, MYSQL users could do the following
$username = mysqli_real_escape_string($_POST['username']);

Another Great option, is with the mysqli adapter, you can use prepared statements. Google this for more info.

2. Cross Site Scripting (XSS)
XSS is another very common vulnerability. This happens when the developer output's variable data without escaping it first.

echo $_POST['searchKeywords'];

Now lets see what happens when an attacker messes with this script.

If the attacker enters javascript into the search box, this script will echo that javascript onto the page. What is the harm in this?
You have just created an XSS hole in your site. This allows attackers to send links to this page with javascript vars that can do all sorts of harmful things like steal cookies, and now by including external js files, make AJAX requests that can make self propagating worms, or just mess with the users account, or post spam, anything really, you have control over them.

A common misconception is XSS is only javascript. XSS is any sort of scripting, even HTML!! Imagine a user using CSS to completely deface your page, or change text on your page, or even change out advertisements!

To mitigate these, make sure you escape all output, trust nothing, here is a fixed example.
echo htmlspecialchars($_POST['searchKeywords']);

3. Remote File Inclusion/Local File Inclusion

RFI/LFI is another very common, and very critical error. Lets have a look at some vulnerable code.


include($BASE_DIR . "/headercontent.php");


This is a common mistake on header/footer and other include files that are not meant to be called alone. There is no declaration for $BASE_DIR in this file. Now remember, we can use get style URL's to set variables in a script. So lets see our attacker at work.

An attacker calls,
now our include looks like this.

So now it includes a file off the attackers website. But why a txt file? PHP is executed serverside, so you will not see the source, but if you put the source of say.. a webshell into a text file, and include that text file, the php inside will be executed.
So what about the ? , well this means any extra data added on by the script will be turned into a get variable, so it doesn't interfere with the URL.

To stop RFI's, you can set php.ini to not allow include remote files, but you may need this, so just make sure you check to make sure the page is being called from another script, like this.
// main.php

defined('SAFE_CALL') or die("Hack Attempt");

Lets have another example.
$page = $_GET['page'];

Who has been guilty of this? :) Well this my friends is an LFI. Lets see our attacker again.

The attacker visits
Now our include looks like this

Yes the transversal pages/../ will work! So this go back a directory, then into the 'secret' directory, and show us the contents of the .htaccess , the attacker can then find the location of the .htpasswd and find it as well.

Now think about the attacker calling this

To fix this, don't use variables in include statements, rather use a switch like this instead
switch($_GET['page']) {
 case "bio":
	$page = "bio.php";
	 $page = "home.php";


4. NullByte

Lets have a look at a similiar exam to above.

$page = $_GET['page'];

Clever eh? Adding info on the end? Well php uses file i/o to do includes, and they have a serious weakness, when they encounter a nullbyte %00 they will terminate. Lets see what our attackers up to.

Our attacker goes to
Same great htaccess include, but this time it's padded on the end with that nullbyte. Now our include looks like this.

When it goes to include that file, the filesystem will go until it hits the nullbyte and then terminate, effectively including everything before it, which is pages/../secret/.htaccess. Nice huh?

To fix this is the same as above, don't use variables in include statements, instead use a switch.

5. Remote Command Exectution

This one is simple.
$dir = $_GET['dir'];
system(ls $dir);

Using variables in any system or command execution is a no no, here is why.

Our attacker visits rm -rf /

eek! Operators like && || allows multiple command execution on one command line, so your attacker just removed everything!

To fix it, just plain simple, do not EVER use variable data in system calls or command execution.

6. Session Hijacking / Cookie Stealing

This is more informative than including samples. Sessions use ID's stored in cookies, or in GET/POST variables that associate a user with an ongoing session. When an attacker acquires this ID, they can modify their cookie or variables to be that stolen ID, then they will take over the session, and credentials, of the original owner. So by changing that ID, they can become the victim.

The same thing for cookie stealing, when programmers use cookies to store user data, then use the cookie data to determine things like who you are, and other important details.

To fix this, always regenerate session ID's on each request, as well as when a user authenticates with your site regenerate the ID, and set a session variable as a fingerprint, that includes things like browser data, blocks of user's IP and a random salt, and then on each request compare the sessions fingerprint with the users fingerprint to make sure they match.

For cookie stealing, always use session variable, it is the only trust able storage option for user information, since it cannot be directly manipulated by the user.

7. Session Fixation
This works when you do not regenerate the session ID when someone authenticates. For example, the attacker sends his friend a link to here His friend visits the site, then logs in on the site. Now the attacker can just follow the same URL to gain control of his friends authenticated session!

to fix this, always regenerate session id's whenever a user authenticates with you.

8. HTTP Response Splitting

Take the following
header ("Location: " . $_GET['page']);

You see, we know the attacker loves unfiltered variables. What we know about HTTP responses is that /r/n in the response can be used to add variables to it.

So if the attacker visits text/html%0d%0aHTTP/1.1 200 OK%0d%0aContent-Type: text/html%0d%0a%0d%0a%3Chtml%3E%3Cfont color=red%3Ehey%3C/font%3E%3C/html%3E

You can see the Content-Type:text/html And the following markup would be displayed, causing an XSS attack.

Simple enough?

Is this repetitive? Never use unfiltered data in an outside functions.

To fix this do not use variable data in header() functions.


Well that about does it. I hope this gave you a good primer to security with php and that you won't make these mistakes and put your applications and servers at risk.

Is This A Good Question/Topic? 3
  • +

Replies To: PHP Security Crash Course

#2 RodgerB   User is offline

  • D.I.C Lover
  • member icon

Reputation: 66
  • View blog
  • Posts: 2,284
  • Joined: 21-September 07

Posted 17 May 2008 - 08:31 PM

Fantastic tutorial! Thanks for the information. :)
Was This Post Helpful? 0
  • +
  • -

#3 spearfish   User is offline

  • Monkey in Training
  • member icon

Reputation: 10
  • View blog
  • Posts: 746
  • Joined: 10-March 08

Posted 18 May 2008 - 05:40 PM


:Goes and rewrites entire site:
Was This Post Helpful? 0
  • +
  • -

#4 godprobe   User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 5
  • Joined: 06-May 08

Posted 20 May 2008 - 02:51 PM

beautiful! thank you!
was looking this stuff up all day yesterday (though not PHP-specific)
most of the info I found (though still applicable) was old
however, one really interesting resource I found was this site...
Was This Post Helpful? 0
  • +
  • -

#5 silverblaze   User is offline

  • D.I.C Head

Reputation: 5
  • View blog
  • Posts: 69
  • Joined: 18-January 08

Posted 21 May 2008 - 12:48 PM

jst want to say amazing..
i had written almost 15-20 full site codes including social n/w, filehosting etc. bt i havnt noticed anythin yet other that the mysql escape.
Any way its really informative and I AM ON A MISSION NOW. to know more about the securty hole and threats in php. Thanks for a good start and remind me about one of the basics i forget to check.
I will let you guys kne if i find some nice informations.
Was This Post Helpful? 0
  • +
  • -

#6 chili5   User is offline

  • D.I.C Lover

Reputation: 20
  • View blog
  • Posts: 1,146
  • Joined: 28-December 07

Posted 22 May 2008 - 04:08 AM

Wow that is very informative.

*bookmarks page*

I now think I have a lot of changes to make in my code.
Was This Post Helpful? 0
  • +
  • -

#7 Ricendithas   User is offline

  • D.I.C Head

Reputation: 0
  • View blog
  • Posts: 59
  • Joined: 12-July 08

Posted 19 July 2008 - 10:41 PM

Thanks for this wonderful tutorial. :)
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1