2009-05-01

Securing Php Web Applications

PHP is a popular server side scripting language, it's as simple or as complex as you want to make it. It is typically used along with Linux, Apache Web server and MySQL RDBMS. In most web applications the script acts on user provided information and returns processed data. To this end there are a number of simple steps you can take to help make your web application less vulnerable to exploitation by an unfriendly party.

This article is intended for beginning to intermediate web application programmers.

=======ToC=========
1. Introduction
2. Methods of input
3. Input data validation
4. Trusted processing
5. Database queries
6. Raising the bar
7. Informative resources
===================
1. Introduction

PHP is a HTML pre-processor, meaning that it reads a file before it is sent to the user and if it contains PHP script, it processes it and returns the document and the processed results to the user. There are many other technologies which do the same thing each with their benefits and flaws. The importance here is not to proclaim the benefits of PHP over the others but to show some good ideas of how to protect your applications from un-friendlies.

2. Methods of input

In PHP we can get information externally from the webserver itself ($_SERVER), Cookies ($_COOKIE), Get variables ($_GET), Post Variables ($_POST) . In addition PHP can internally connect to just about anything.

Example:
So when Joe, our end user goes to your website to check this weeks Fantasy Football scores on your website, he will login (sending login information using POST variables) to a script which then reads the login information and decides whether he can login. Then it returns a page with the result of his attempt and then either takes him to the next page or back to the login prompt. Once he is logged in, PHP sets a Cookie with a unique random session id. Every time a browser returns that cookie to a page, it knows that this session is good and belongs to Joe. Then Joe sorts his results page sending some criteria via a Get variable which is used to control a query to the sports database.

The important thing to know is that Joe can control everything he sends to the server. He can see the cookie contents, post data and get variables. Lets say that Joe wants to check a friends team score. The site allows Joe to sort his scores using GET variables. Joe just places in an escape character and appends some SQL to view his friends score.

3. Input data validation

Think of a web application like a game of D&D, if you are out on the desert plains with a 12th level Barbarian named Ogar, whats keeping the player from making Ogar go left when the DM expects the player to go right? There is no reason Ogar the barbarian can't sit down and whittle a set of dice, mark up a parchment with character stats and then play Cube farms & Bosses.

You have a nice HTML page which provides for the intended actions of the user but everything in the browser or on the computer is out of your control. Java script, plug ins, input, cookies and URLs are not controllable and therefore cannot be fully trusted.

The key is limiting the users choices, and abstracting their decisions. If your scripts inputs expect a phone number, then the input should only be numbers or else its invalid. If there is only search methods A,B or C then if the input isn't A,B or C then it has to be invalid. Simply filtering out known bad data such as embedded javascript isn't 100% effective, if the data type is contaminated it cannot be trusted.

The quality of the data you take in is important, the other part of this is abstraction of the users decisions. If a persons available choices are A,B and C, and internally you identify A, B and C as actions and everything else as false input then that is more effective than allowing user input directly control your data.

4. Trusted processing

Assuming that you have done your due diligence and secured your server, it is more trustworthy of a computing platform than your clients workstation. A clients workstation could be infected with mal-ware, it could have a malfunctioning or obsolete browser or the user could intentionally manipulate the http variables to trick the application. Input validation cannot be done using JavaScript alone, trusting JavaScript or any other plug in to obfuscate your applications process just isn't a good idea. Client side scripting is good for enhancing the presentation and for providing a means to communicate information effectively to the user but it should not be relied upon to process information.

5. Database queries

Filtering valid data is just one step, the other step is on your data sources such as MySQL, Postgres, Oracle ... most modern Databases allow you to do a prepared statement which auto-magically binds input into a SQL string. Because its binding data directly to a variable the chances that a user's escape string can hijack the SQL query is greatly diminished. By limiting the users input to only data and not to the program execution process you greatly reduce the possibility of your script becoming compromised.

For example:

"http://example.com/mypage.php?display=select * from mydatabase.mytable where user=Joe order by date;"

Including SQL in a user accessible variable is a really really bad idea. Even if it is on a link that Joe wont see and Java script is used to obscure the URL. Joe controls the machine so any obfuscation used will never be effective. What is stopping Joe from substituting "select 'joe' as user password as score, currdate() as date from mysql.users where username=root;"?

6. Raising the bar

There are alot of "Magic Bullet" solutions to web application security. Application firewalls monitor information going both to and the web application. SQL application firewalls filter out suspicious SQL commands going to your RDBMS server. For most developers, these solutions are
either too expensive or too complex to implement for individual web applications. Here are some PHP security plug ins and tools to help raise the bar on the cheap.

When you use this or any other security plug-in, it is vital that you evaluate your applications baseline performance to know what is normal behavior. For instance PHPBB2, a popular PHP bulletin board application display a large list of forums. And mysteriously the settings would not save. I was using Suhosin and this was caused because the number of variables being posted was above Suhosin's default limit and the script was aborting before it could save the changes.

On the server side there is Green SQL, which is a MySQL sanitizer/proxy. Then there is mod_security which hardens Apache and turns it into an application firewall. mod_chroot is similar in the basic functionality of mod-security except it just chroots Apache transparently to the user. Then there are web application security scanners such as the ones included in Nesssus.

Wapiti checks for cross-site scripting (XSS), injection and other common issues. OWASP's WebScarab is a good utility for testing user access to http variables on the client side and intercepting the raw http conversation between the client and the server.

7. Informative resources


Breach Security "Mod Security home page". (Accessed April 2009)
http://www.modsecurity.org

Dawes, Rogan "OWASP WebScarab Project" (Accessed April 2009)
http://www.owasp.org/index.php/Category:OWASP_WebScarab_Project

Esser, Stefan "Hardened PHP Project" (Accessed April 2009)
http://www.hardened-php.net/suhosin/

Freitag, Pete "20 ways to Secure your Apache Configuration" (Accessed April 2009)
http://www.petefreitag.com/item/505.cfm (Posted Dec 5, 2005)

Green SQLProject "Green SQL home page". (Accessed April 2009)
http://www.greensql.net

Hobbit "mod_chroot" (Accessed April 2009)
http://core.segfault.pl/~hobbit/mod_chroot/


OWASP Foundation. "Main Page" (Accessed April 2009)
http://www.owasp.org/index.php/Main_Page

Tenable network security inc. "Nessus Product Page" (Accessed April 2009)
http://www.nessus.org/nessus/

The Apache Foundation. "Apache HTTP Server Project". (Accessed April 2009)
http://httpd.apache.org/

The PHP Group. "PHP: Hypertext Preprocessor". (Accessed April 2009)
http://www.php.net/

Surribas, Nicolas "Wapiti Web application vulnerability scanner / security auditor" (Accessed April 2009)
http://wapiti.sourceforge.net/

See also:
Ax0n's OAMP (Apache, Mysql, PHP on OpenBSD) Article:
http://www.h-i-r.net/2008/12/sysadmin-sunday-amp-on-openbsd-44.html

Asmodian X's Name based hosting mini-howto:
http://www.h-i-r.net/2008/10/sysadmin-sunday-apache-name-based.html

Asmodian X's Workbench - Suhosin :
http://www.h-i-r.net/2008/12/asmodians-workbench-suhosin-hardened.html

blog comments powered by Disqus