bckurera's thoughts

Just another WordPress.com site

CAPTCHA with no $_SESSION

Due to the nature of the stateless behavior of HTTP, managing the current state of a connected user is a tricky scenario to handle in web site development or rather in web application development.

Few solutions are in place already and $_SESSION is one of the ways available in PHP. $_SESSION, the global array is not my favorite choice but it is handy. The sever based session management approach is not 100% reliable but it would do the work in most of the cases.

On the other hand, distinguishing user inputs versus inputs from malicious bots seems quite challenging these days. Simple tricks such as “honeypot” are quite old and easy to overcome, of course bots are now capable enough to skip “honeypots” without much effort. Then comes much promising solutions such as Google’s new invention, reCAPTCHA where a sophisticated techniques can identified the origin of the inputs blocking spams on your site, web application etc.

However life is not that easy, there are plenty of scenarios where we need to come up with our own strategy to deal with these inputs. If you cannot use reCAPTCHA or any other 3rd party CAPTCHA solution then the best would be implementing one of your own. This is the riskiest but there can be instances that this is the only way forward. I was in such a situation few months back and I though of sharing how I overcame it.

Avoiding $_SESSION

It is not hard to find plenty of tutorials to follow, implementing simple CAPTCHA verification in PHP. Almost every solution is based on $_SESSION, using server based sessions, a global array in PHP. This is easy and simple. Few lines of code would do the trick. As same as the way mentioned in this article. I am not a fan of server based sessions therefore I wanted to skip it.

In this post I am trying to explain how I solved the stateless issue without using server based sessions.

Breaking the Problem

The main issue that we need to solve is identifying the legitimate requests/ inputs and filter out the rest. In order to achieve this, when the relevant input form has been requested by a client, the server adds an image which is a human readable text. Bots may not be able to identify what is in it. Then the user inputs the code and sends the request to the server. As it is not possible to include the verification code in the client side request, the server doesn’t know what has been sent earlier. That is where server based sessions comes for the rescue. It is possible to store the verification code in a session variable.  Then when the user has submitted the form, the server can simply checks if the entered verification code value matches the value in the session. If so it is a human, test passes. Since we are trying to omit using server based sessions, we need to come up with a way to identify what has been sent earlier.

Solution

Step 1

Following is a typical code snippet (captcha.php) to create the CAPTCHA image. It is pretty straight forward and it can be seen that the verification code has been assigned to the session variable, $_SESSION[‘rand_code’] = $string;

<?php
session_start();

$string = '';

for ($i = 0; $i < 5; $i++) {     // this numbers refer to numbers of the ascii table (lower case)
$string .= chr(rand(97, 122)); }   
$_SESSION['rand_code'] = $string;   
$dir = 'fonts/';   
$image = imagecreatetruecolor(170, 60); 
$black = imagecolorallocate($image, 0, 0, 0); 
$color = imagecolorallocate($image, 200, 100, 90); // red 
$white = imagecolorallocate($image, 255, 255, 255);   imagefilledrectangle($image,0,0,399,99,$white); 
imagettftext ($image, 30, 0, 10, 40, $color, $dir."arial.ttf", $_SESSION['random_code']);   
header("Content-type: image/png"); 
imagepng($image); 
?>

Following shows how it has been included in the HTML, client side.

<form action="<?php echo $_SERVER['PHP_SELF']; ?>
" enctype="multipart/form-data" method="post"><input name="name" type="text" />

<input name="email" type="text" />

<textarea name="message"></textarea>

<img src="captcha.php" />

<input name="code" type="text" />

<input name="submit" type="reset" value="Send" />
</form>

When analyzing the HTML code, you will soon realize that the code can be exploited simply with a Cross Site Scripting (XSS) attack as it barely uses $_SERVER[‘PHP_SELF’] in form action. I will not be focusing on that since I am not going to use sessions here. Following is the modified prototype version.

Step 2

I have changed the client side code as follow. Notice that a hidden filed has been introduced. A randomly generated number with hash coded act as the reference id here. The reference has been passed when creating the CAPTCHA image and also it gets submitted when the user submits the form.

<?PHP
require_once 'dataBaseConnection.php';
<form action="verify.php" enctype="multipart/form-data" method="post">
Name: <input name="name" type="text" />

Email <input name="email" type="text" />

Message
<textarea name="message"></textarea>

<!--?PHP   $captchaId = sha1(rand(1000000,9999999).time());  dataBaseConnection::registerReference($captchaId);  $path='captcha.php?ref='.$captchaId;   ?--> <img src=""<?PHP" /> "/>
Enter the above code
<input name="c_id" type="hidden" value="<?PHP echo $captchaId; ?>" />

<input name="code" type="text" />

<input name="submit" type="submit" value="Send" />

and then the captcha.php has been modified too.

<?php
$string = '';
$refCode = '';

if(isset($_GET['ref']))
{
$refCode = $_GET['ref'];
}else{
die('<error>NO REF CODE FOUND !</error>');
}

for ($i = 0; $i < 8; $i++)
{
// this numbers refer to numbers of the ascii table (lower case)
$string .= chr(rand(97, 122));
}

$dir = 'fonts/';

$image = imagecreatetruecolor(170, 60);
$black = imagecolorallocate($image, 0, 0, 0);
$color = imagecolorallocate($image, 10, 10, 10); // red
$invColor = imagecolorallocate($image, 200, 200, 200); // invisible_ink
$white = imagecolorallocate($image, 255, 255, 255);

imagefilledrectangle($image,0,0,399,99,$white);
for($i=0; $i<100; $i++) 
{ 
imagettftext ($image, 20, rand(0,10), 0, $i*10, $invColor, $dir."ts.ttf", 'xxxxxxxxxxxxxxxxxxxxxxxxx'); 
} 
imagettftext ($image, 30, 2, 10, 40, $color, $dir."ts.ttf", $string);
header("Content-type: image/png"); 
imagepng($image); 
require_once 'dataBaseConnection.php'; dataBaseConnection::addVerificationCode($refCode, $string); //store the reference and the code in the database 
?>

The static methods dataBaseConnection::registerReference stores the reference code which will later be an input to captcha.php. The system automatically logs the timestamp and set the status of the record to ‘CREATED’. Then in the captcha.php file static method dataBaseConnection::addVerificationCode adds the generated verification code to the relevant reference .

Step 3

Then comes the verify.php code which validates the entered code against the code in the database.

<?php require_once 'dataBaseConnection.php'; if(isset($_POST['submit']))   {  	$enteredCode=trim($_POST['code']);  	$referenceCode=trim($_POST['c_id']);     $dataSet = dataBaseConnection::getCode($referenceCode);     $timeTaken = time() - $dataSet['pvt_created_date'];     if($timeTaken>$dataSet['pvt_life_time'] || $dataSet['pvt_captcha_status']!='CREATED')
    {
    	die('expired code');
    }

    //var_dump($referenceCode); die($enteredCode);
	if($enteredCode==$dataSet['str_verification_code'])
	{
		dataBaseConnection::updateCode($referenceCode,'VERIFIED');
		echo 'verified';//this is a human
		//Process the input as this is a legit request
	}else{
		dataBaseConnection::updateCode($referenceCode);
		echo 'not verified';//most probably not a human
	}
}
?>

If both codes match then the static method dataBaseConnection::updateCode changes the status of the verification code to ‘VERIFIED’ in the database while the status has been set to ‘USED’ for the verification code if they dont match. That expires the verification code and it will not be possible to use it again. Further there is a check to make sure that the code has not been expired too.

How secure this is

It is not difficult to train a bot to reading CAPTCHAs. Therefore to make this much stronger it is required to have an image with higher entropy.

Another weak point is, the reference code is getting exposed to the attacker. However there reference number has no relationship with the code. Therefore the attacker cannot predict the code by cracking the reference code. This is possible as we store the reference and the verification code in the database.

An attacker cannot use a brute force attack as the status of the verification code has been updated after an attempt has been made disregarding the results. So once tried the code is set to expired. Setting lifetime of the code can be used to limit the time available for the attacker to crack the image. In this case 300 seconds.

Further it is required to restrict direct access to captcha.php file from the outside, simply using .htaccess entry. Otherwise it is possible to carry out a Denial-of-service attack targeting the generation of the captcha image which in return could have lead to a database failure.

It is important to track client details but will discuss it in another post.

Conclusion

How to implement a captcha verification solution without using server based sessions has been discussed above. Complete source code can be found here. Please check it out and let me know any flaws you observe. This is a mere implementation of the concept and no other aspects were considered when developing the code and no proper testing has been carried out. Therefore if you are going to use it in your code please be careful unless you know what you are doing.

1 Comment »

__construct() in PHP, OOP with PHP

In PHP it is possible to use the construct method which is really useful, in java we can have several constructor methods and the rule is the method name should be as same as the class name. In PHP the rule is quite different. It uses a special method __construct which is called once an object is created or simply when new operator is used. Therefore this method is also known as “magic method” and it is one of the few magic methods in PHP.

Without further text, following would be an example of using constructor method with in PHP OOP.

class Cube1 {

	private $length;
	private $depth;
	private $height; 
	
	public function __construct() {
		$this->length = 10;
		$this->depth = 10;
		$this->height = 10;
	}
	
	public function getVolume() {
		return ($this->length * $this->depth * $this->height);
	}
}

$box=new Cube1();
echo $box->getVolume();

This looks really simple. How would it be if we need to have more than one constructor methods which can accept arguments.

class Cube1 {

	private $length;
	private $depth;
	private $height; 
	
	public function __construct($a=10,$b=10,$c=10) {
		$this->length = $a;
		$this->depth = $b;
		$this->height = $c;
	}
	
	public function getVolume() {
		return ($this->length * $this->depth * $this->height);
	}
}

$box=new Cube1(10,2.5);
echo $box->getVolume();

$box2=new Cube1(2);
echo $box2->getVolume();

Since in PHP the __construct method cannot be override directly as in Java but there are few techniques to use so that it is possible in the indirect way. Will discuss them in the next post.

It is up to you to use your imagination and creativity to make use the of this feature.

1 Comment »

Hope this is the time to discuss the PHP Hack Challenge I and at the moment we have discussed this in the class. For others benefit who read my blog I think of noting the discussion.

If you find any other way of smart thinking please let me know, a simple comment will do it.

Code

<?php $_F=__FILE__;$_X='Pz4JCTxkNHYgY2wxc3M9ImNsNTFyIj48L2Q0dj4NCgk8L2Q0dj48IS0tIC9jMm50MTRuNXIgLS0+DQoNCgk8ZDR2IDRkPSJmMjJ0NXIiPg0KDQo8c3AxbiA0ZD0iYmwyZy1uMW01Ij48P3BocCBibDJnNG5mMignbjFtNScpOz8+PC9zcDFuPiA8P3BocCBibDJnNG5mMignZDVzY3I0cHQ0Mm4nKTsgPz4gQzJweXI0Z2h0ICZjMnB5OyA8P3BocCA1Y2gyIGQxdDUoJ1knKTs/PiAtIDwxIGhyNWY9Imh0dHA6Ly90MnB3cHRoNW01cy5jMm0iIHQ0dGw1PSJXMnJkcHI1c3MgVGg1bTVzIiB0MXJnNXQ9Il9ibDFuayI+VzJyZHByNXNzIFRoNW01PC8xPiBkNXY1bDJwNWQgYnkgPDEgaHI1Zj0iaHR0cDovL3d3dy53NWJoMnN0NG5nZjFuLmMybSIgdDR0bDU9Ilc1YiBIMnN0NG5nIEYxbiIgdDFyZzV0PSJfYmwxbmsiPlc1YiBIMnN0NG5nIEYxbjwvMT4NCgk8L2Q0dj48IS0tIC9mMjJ0NXIgLS0+DQo8L2Q0dj48IS0tIC93cjFwcDVyIC0tPg0KPC9kNHY+PCEtLSAvYjJkeS00biAtLT4NCjw/cGhwIHdwX2YyMnQ1cigpOyA/Pg0KPC9iMmR5Pg0KPC9odG1sPg==';eval(base64_decode('JF9YPWJhc2U2NF9kZWNvZGUoJF9YKTskX1g9c3RydHIoJF9YLCcxMjM0NTZhb3VpZScsJ2FvdWllMTIzNDU2Jyk7JF9SPWVyZWdfcmVwbGFjZSgnX19GSUxFX18nLCInIi4kX0YuIiciLCRfWCk7ZXZhbCgkX1IpOyRfUj0wOyRfWD0wOw=='));?>

As the first step we should identified what are in the code snippet. We can use ; to separate lines. May be then we can see things clearly.

<?php
$_F=__FILE__;
$_X='Pz4JCTxkNHYgY2wxc3M9ImNsNTFyIj48L2Q0dj4NCgk8L2Q0dj48IS0tIC9jMm50MTRuNXIgLS0+DQoNCgk8ZDR2IDRkPSJmMjJ0NXIiPg0KDQo8c3AxbiA0ZD0iYmwyZy1uMW01Ij48P3BocCBibDJnNG5mMignbjFtNScpOz8+PC9zcDFuPiA8P3BocCBibDJnNG5mMignZDVzY3I0cHQ0Mm4nKTsgPz4gQzJweXI0Z2h0ICZjMnB5OyA8P3BocCA1Y2gyIGQxdDUoJ1knKTs/PiAtIDwxIGhyNWY9Imh0dHA6Ly90MnB3cHRoNW01cy5jMm0iIHQ0dGw1PSJXMnJkcHI1c3MgVGg1bTVzIiB0MXJnNXQ9Il9ibDFuayI+VzJyZHByNXNzIFRoNW01PC8xPiBkNXY1bDJwNWQgYnkgPDEgaHI1Zj0iaHR0cDovL3d3dy53NWJoMnN0NG5nZjFuLmMybSIgdDR0bDU9Ilc1YiBIMnN0NG5nIEYxbiIgdDFyZzV0PSJfYmwxbmsiPlc1YiBIMnN0NG5nIEYxbjwvMT4NCgk8L2Q0dj48IS0tIC9mMjJ0NXIgLS0+DQo8L2Q0dj48IS0tIC93cjFwcDVyIC0tPg0KPC9kNHY+PCEtLSAvYjJkeS00biAtLT4NCjw/cGhwIHdwX2YyMnQ1cigpOyA/Pg0KPC9iMmR5Pg0KPC9odG1sPg==';
eval(base64_decode('JF9YPWJhc2U2NF9kZWNvZGUoJF9YKTskX1g9c3RydHIoJF9YLCcxMjM0NTZhb3VpZScsJ2FvdWllMTIzNDU2Jyk7JF9SPWVyZWdfcmVwbGFjZSgnX19GSUxFX18nLCInIi4kX0YuIiciLCRfWCk7ZXZhbCgkX1IpOyRfUj0wOyRfWD0wOw=='));
?>

now you can see things more clear way2 variables and then eval() is used with base64_decode(). Therefore we can use base64_decode() and see what is in the eval()

if you run following snippt you can get the code encoded by base64.

<?PHP
$txt= base64_decode('JF9YPWJhc2U2NF9kZWNvZGUoJF9YKTskX1g9c3RydHIoJF9YLCcxMjM0NTZhb3VpZScsJ2FvdWllMTIzNDU2Jyk7JF9SPWVyZWdfcmVwbGFjZSgnX19GSUxFX18nLCInIi4kX0YuIiciLCRfWCk7ZXZhbCgkX1IpOyRfUj0wOyRfWD0wOw==');
echo $txt;
?>

The output would be

$_X=base64_decode($_X);$_X=strtr($_X,'123456aouie','aouie123456');$_R=ereg_replace('__FILE__',"'".$_F."'",$_X);eval($_R);$_R=0;$_X=0;

again if we separate them using ; , following would be the result,

$_X=base64_decode($_X);
$_X=strtr($_X,'123456aouie','aouie123456');
$_R=ereg_replace('__FILE__',"'".$_F."'",$_X);
eval($_R);$_R=0;$_X=0;

Then if you check the original code you will see two variable $_F and $_X are also available.

$_X is base 64 encoded, will decode and see what it contains.

This is the output.

?>		<d4v cl1ss="cl51r"></d4v>
	</d4v><!-- /c2nt14n5r -->

	<d4v 4d="f22t5r">

<sp1n 4d="bl2g-n1m5"><?php bl2g4nf2('n1m5');?></sp1n> <?php bl2g4nf2('d5scr4pt42n'); ?> C2pyr4ght &c2py; <?php 5ch2 d1t5('Y');?> - <1 hr5f="http://t2pwpth5m5s.c2m" t4tl5="W2rdpr5ss Th5m5s" t1rg5t="_bl1nk">W2rdpr5ss Th5m5</1> d5v5l2p5d by <1 hr5f="http://www.w5bh2st4ngf1n.c2m" t4tl5="W5b H2st4ng F1n" t1rg5t="_bl1nk">W5b H2st4ng F1n</1>
	</d4v><!-- /f22t5r -->
</d4v><!-- /wr1pp5r -->
</d4v><!-- /b2dy-4n -->
<?php wp_f22t5r(); ?>
</b2dy>
</html>

Therefore the $_X contains a HTML code. The next thing is to deal with the strtr() function. The beauty of this function is it replace 1 with a, 2 with o, 3 with u like that.

$_X=strtr($_X,'123456aouie','aouie123456');

Therefore after running this function the $_X will be converted as below.

?>		<div></div>
	</div><!-- /container -->

	<div id="footer">

<span id="blog-name"><?php bloginfo('name');?></span> <?php bloginfo('description'); ?> Copyright &copy; <?php echo date('Y');?> - <a href="http://topwpthemes.com" title="Wordpress Themes" target="_blank">Wordpress Theme</a> developed by <a href="http://www.webhostingfan.com" title="Web Hosting Fan" target="_blank">Web Hosting Fan</a>
	</div><!-- /footer -->
</div><!-- /wrapper -->
</div><!-- /body-in -->
<?php wp_footer(); ?>
</body>
</html>

Above is the code that tried to hide using base64 encode and use eval to execute the code.

__FILE__ is called as Magic Constants and I have discussed them earlier in this blog.

However in this code snippt it is easy to breat it as you can see the base64_decode function if that function cant be seen then you are in a bit trouble. In such cases you have to examine the encoded text. Most of the time if you can see = or == at the end of the text, that can be encoded using base64. So it is better to try it first.

Apparently think what are the further actions that can be taken to increase the quality of the code.

Leave a comment »

PHP Hack Challenge I

As I have promised in the Wed Development class I have added the PHP code that should be hacked. Use comments to discuss the related stuffs.

“I have no idea what this is; so can you please show me what is this?”

If anyone find out the answer put it as a comment and nobody can see it until the next class. Lets discuss this on the next class before that hack it. I have a price, open to Web Development class students.

Challenge: if you are smart you can do it within, ok lets say 15 mins. 😉

Language is PHP.

<?php $_F=__FILE__;$_X='Pz4JCTxkNHYgY2wxc3M9ImNsNTFyIj48L2Q0dj4NCgk8L2Q0dj48IS0tIC9jMm50MTRuNXIgLS0+DQoNCgk8ZDR2IDRkPSJmMjJ0NXIiPg0KDQo8c3AxbiA0ZD0iYmwyZy1uMW01Ij48P3BocCBibDJnNG5mMignbjFtNScpOz8+PC9zcDFuPiA8P3BocCBibDJnNG5mMignZDVzY3I0cHQ0Mm4nKTsgPz4gQzJweXI0Z2h0ICZjMnB5OyA8P3BocCA1Y2gyIGQxdDUoJ1knKTs/PiAtIDwxIGhyNWY9Imh0dHA6Ly90MnB3cHRoNW01cy5jMm0iIHQ0dGw1PSJXMnJkcHI1c3MgVGg1bTVzIiB0MXJnNXQ9Il9ibDFuayI+VzJyZHByNXNzIFRoNW01PC8xPiBkNXY1bDJwNWQgYnkgPDEgaHI1Zj0iaHR0cDovL3d3dy53NWJoMnN0NG5nZjFuLmMybSIgdDR0bDU9Ilc1YiBIMnN0NG5nIEYxbiIgdDFyZzV0PSJfYmwxbmsiPlc1YiBIMnN0NG5nIEYxbjwvMT4NCgk8L2Q0dj48IS0tIC9mMjJ0NXIgLS0+DQo8L2Q0dj48IS0tIC93cjFwcDVyIC0tPg0KPC9kNHY+PCEtLSAvYjJkeS00biAtLT4NCjw/cGhwIHdwX2YyMnQ1cigpOyA/Pg0KPC9iMmR5Pg0KPC9odG1sPg==';eval(base64_decode('JF9YPWJhc2U2NF9kZWNvZGUoJF9YKTskX1g9c3RydHIoJF9YLCcxMjM0NTZhb3VpZScsJ2FvdWllMTIzNDU2Jyk7JF9SPWVyZWdfcmVwbGFjZSgnX19GSUxFX18nLCInIi4kX0YuIiciLCRfWCk7ZXZhbCgkX1IpOyRfUj0wOyRfWD0wOw=='));?>
1 Comment »

Web Security – The Big Picture

These days I am into studying about Web Security(under the Web Security course module of the Northubria University- MIS) and found it is so interesting. Therefore I think of writing a little about the Web Security. Being specific I try to write appropriately to PHP.

In world wide web, this can be found as PHP hack and I was interested in getting knowing how the PHP hack can be eliminated. Knowing those are very important and that will help you to design and develop a PHP hack free web site if your scripts are in PHP. When reading keep in your mind that I am new to those stuffs.

There is no use of talking about SQL Injection attacks as nobody now use eval to process form’s data. Therefore for the time being I skipped that and if you are interesting enough please google.

Forms fields are an important place where the developers should have good attention. For an instance lets consider the following situation. A field where use to enter the address of the user. The entered values are checked against a length and if the ore0defined length is exceeded it is considered that the input is valid. However this seems pretty enough to verify that the user enter his address as long as the address doesnt carry and defined format. Bare mind I am talking about his snail mail address. Even tough it is validating the input it doesnt verify that the input is risk free.

What happen if a user added some HTML or Javascript code, then the code is stored in the database and rendered when data is requested. That can lead to serious problems. Therefore the possibility to enter markups or codes should be eliminated.

With no sofisticated functions that can be achieved using simple str_replace. Following code will do what is needed.

str_replace(‘<','',$_POST['address']);

If you like following function are also in your side. Please try them and see.

strip_tags()
nl2br()
htmlspecialchars()

Further please do not use eval() function if you dont have much understanding about the function or related security risk. My free advise is use eval if you have no choice ONLY. Not only that but also following functions as well, system(), passthru() and exec().

Another important function is escapeshellarg(). There any ', ; or " is replaced with \' , \" , \;

Avoid using GET to send form data and use POST method instead. However in some situation POST is not possible, unless in such situations always try to use POST method for form data submission.

With experience I knew that most of the developers limit the size of the form in HTML interface and never try to check it again in the server side. They use Javascript to check the length on the client side and never check it again in the server side.

This is not a good practice, each and every test you perform on the client side should be followed on the server side as well. Otherwise intruders can bypass the browser and send false info to the server as long as the server is blind and not checking the input, thinking checking them on the client side would be enough. Therefore you need to have better security not only on the client side but mostly on the server side.

Looking forward to write more soon, keep reading . .

Leave a comment »

How to find the origin?

Today one student from the Web Development class asked me “how web sites are detecting referrals?”, this is a nice question and though of giving the answer publicly so that anyone can get the benefit.

First of all will discuss what this is?

May be you have experienced when you visit to a web site it says where you come from, for an instance assume that you click on a Google search then the site knows that you come through Google. This is a very important thing in SEO as well.

The code behind is very very simple. What you have to do is just use the ‘HTTP_REFERER’ global variable in the code.

You can find an example below.

$referer = $_SERVER[‘HTTP_REFERER’];
echo “You have came though <br/> ” . $referer;

The output would be the URL which is clicked before you come to the site where the above PHP code is.

Bare mind that the out put is a full qualified URL which has http:// or the protocol in front of the URL. Depending on your imagination this code snippet can be used in various applications.

1 Comment »

Web Security – The Big Picture

These days I am into studying about Web Security(under the course module of the Northubria University- MIS) and found it is so interesting. Therefore I think of writing a little about the Web Security. Being specific I try to write appropriately to PHP.

In world wide web, this can be found as PHP hack and I was interested in getting knowing how the PHP hack can be eliminated. Knowing those are very important and that will help you to design and develop a PHP hack free web site if your scripts are in PHP. When reading keep in your mind that I am new to those stuffs.

There is no use of talking about SQL Injection attacks as nobody now use eval to process form’s data. Therefore for the time being I skipped that and if you are interesting enough please google.

Forms fields are an important place where the developers should have good attention. For an instance lets consider the following situation. A field where use to enter the address of the user. The entered values are checked against a length and if the ore0defined length is exceeded it is considered that the input is valid. However this seems pretty enough to verify that the user enter his address as long as the address doesnt carry and defined format. Bare mind I am talking about his snail mail address. Even tough it is validating the input it doesnt verify that the input is risk free.

Each of these may be verified using regular expressions, which scan the input for certain patterns. An example for e-mail address verification is the PHP code shown below. This evaluates to true if an e-mail address was entered in the field named ’email’.

preg_match(‘/^.+@.+\..{2,3}$/’,$_POST[’email’]);

This code just constructs a regular expression based on the format described above for an e-mail address. Note that this will return true for anything with an @ sign and a dot followed by 2 or 3 characters. That is the general format for an e-mail address, but it doesn’t mean that address necessarily exists; you’d have to send mail to it to be sure of that.

Interesting as this is, how does it relate to security? Well, consider a guestbook as an example. Here, users are invited to enter a message into a form, which then gets displayed on the HTML page along with everyone else’s messages. For now, we won’t go into database security issues, the problems dealt with below can occur whether the data is stored in a database, a file, or some other construct.

If a user enters data which contains HTML, or even JavaScript, then when the data is included into your HTML for display later, their HTML or JavaScript will also get included.

If your guestbook page displayed whatever was entered into the form field, and a user entered the following,

Hi, I love your site.

Then the effect is minimal, when displayed later, this would appear as,

Hi, I love your site.

Of course, when the user enters JavaScript, things can get a lot worse. For example, the data below, when entered into a form which does not prevent JavaScript ending up in the final displayed page, will cause the page to redirect to a different website. Obviously, this only works if the client has JavaScript enabled in their browser, but the vast majority of users do.

Hi, I love your site. Its great!document.location=”http://www.acunetix.com/”;

For a split second when this is displayed, the user will see,

Hi, I love your site. Its great!

The browser will then kick in and the page will be refreshed from http://www.acunetix.com. In this case, a fairly harmless alternative page, although it does result in a denial of service attack; users can no longer get to your guestbook.

Consider a case where this was entered into an online order form. Your order dispatchers would not be able to view the data because every time they tried, their browser would redirect to another site. Worse still, if the redirection occurred on a critical page for a large business, or the redirection was to a site containing objectionable material, custom may be lost as a result of the attack.

Fortunately, PHP provides a way to prevent this style of PHP hack attack. The functions strip_tags(), nl2br() and htmlspecialchars() are your friends, here.

strip_tags() removes any PHP or HTML tags from a string. This prevents the HTML display problems, the JavaScript execution (the tag will no longer be present) and a variety of problems where there is a chance that PHP code could be executed.

nl2br() converts newline characters in the input to
HTML tags. This allows you to format multi-line input correctly, and is mentioned here only because it is important to run strip_tags() prior to running nl2br() on your data, otherwise the newly inserted
tags will be stripped out when strip_tags() is run!

Finally, htmlspecialchars() will entity-quote characters such as and & remaining in the input after strip_tags() has run. This prevents them being misinterpreted as HTML and makes sure they are displayed properly in any output.

Having presented those three functions, there are a few points to make about their usage. Clearly, nl2br() and htmlspecialchars() are suited for output formatting, called on data just before it is output, allowing the database or file-stored data to retain normal formatting such as newlines and characters such as &. These functions are designed mainly to ensure that output of data into an HTML page is presented neatly, even after running strip_tags() on any input.

strip_tags(), on the other hand, should be run immediately on input of data, before any other processing occurs. The code below is a function to clean user input of any PHP or HTML tags, and works for both GET and POST request methods.

function _INPUT($name)
{
if ($_SERVER[‘REQUEST_METHOD’] == ‘GET’)
return strip_tags($_GET[$name]);
if ($_SERVER[‘REQUEST_METHOD’] == ‘POST’)
return strip_tags($_POST[$name]);
}

This function could easily be expanded to include cookies in the search for a variable name. I called it _INPUT because it directly parallels the $_ arrays which store user input. Note also that when using this function, it does not matter whether the page was requested with a GET or a POST method, the code can use _INPUT() and expect the correct value regardless of request method. To use this function, consider the following two lines of code, which both have the same effect, but the second strips the PHP and HTML tags first, thus increasing the security of the script.

$name = $_GET[‘name’);
$name = _INPUT(‘name’);

If data is to be entered into a database, more processing is needed to prevent SQL injection, which will be discussed later.

Executing Code Containing User Input
Another concern when dealing with user data is the possibility that it may be executed in PHP code or on the system shell. PHP provides the eval() function, which allows arbitrary PHP code within a string to be evaluated (run). There are also the system(), passthru() and exec() functions, and the backtick operator, all of which allow a string to be run as a command on the operating system shell.

Where possible, the use of all such functions should be avoided, especially where user input is entered into the command or code. An example of a situation where this can lead to attack is the following command, which would display the results of the command on the web page.

echo ‘Your usage log:
‘;
$username = $_GET[‘username’];
passthru(“cat /logs/usage/$username”);

passthru() runs a command and displays the output as output from the PHP script, which is included into the final page the user sees. Here, the intent is obvious, a user can pass their username in a GET request such as usage.php?username=andrew and their usage log would be displayed in the browser window.

But what if the user passed the following URL?

usage.php?username=andrew;cat%20/etc/passwd

Here, the username value now contains a semicolon, which is a shell command terminator, and a new command afterwards. The %20 is a URL-Encoded space character, and is converted to a space automatically by PHP. Now, the command which gets run by passthru() is,

cat /logs/usage/andrew;cat /etc/passwd

Clearly this kind of command abuse cannot be allowed. An attacker could use this vulnerability to read, delete or modify any file the web server has access to. Luckily, once again, PHP steps in to provide a solution, in the form of the escapeshellarg() function. escapeshellarg() escapes any characters which could cause an argument or command to be terminated. As an example, any single or double quotes in the string are replaced with \’ or \”, and semicolons are replaced with \;. These replacements, and any others performed by escapeshellarg(), ensure that code such as that presented below is safe to run.

$username = escapeshellarg($_GET[‘username’]);
passthru(“cat /logs/usage/$username”);

Now, if the attacker attempts to read the password file using the request string above, the shell will attempt to access a file called “/logs/usage/andrew;cat /etc/passwd”, and will fail, since this file will almost certainly not exist.

It is generally considered that eval() called on code containing user input be avoided at all costs; there is almost always a better way to achieve the desired effect. However, if it must be done, ensure that strip_tags has been called, and that any quoting and character escapes have been performed.

Combining the above techniques to provide stripping of tags, escaping of special shell characters, entity-quoting of HTML and regular expression-based input validation, it is possible to construct secure web scripts with relatively little work over and above constructing one without the security considerations. In particular, using a function such as the _INPUT() presented above makes the secure version of input acquisition almost as painless as the insecure version PHP provides.

How to check for PHP vulnerabilities
The best way to check whether your web site & applications are vulnerable to PHP hack attacks is by using a Web Vulnerability Scanner. A Web Vulnerability Scanner crawls your entire website and automatically checks for vulnerabilities to PHP attacks. It will indicate which scripts are vulnerable so that you can fix the vulnerability easily. Besides PHP security vulnerabilities, a web application scanner will also check for SQL injection, Cross site scripting & other web vulnerabilities.

Acunetix Web Vulnerability Scanner ensures website security by automatically checking for SQL injection, Cross site scripting and other vulnerabilities. It checks password strength on authentication pages and automatically audits shopping carts, forms, dynamic content and other web applications. As the scan is being completed, the software produces detailed reports that pinpoint where vulnerabilities exist. Take a product tour or download the evaluation version today!

Scanning for XSS vulnerabilities with Acunetix WVS Free Edition!
To check whether your website has cross site scripting vulnerabilities, download the Free Edition from http://www.acunetix.com/cross-site-scripting/scanner.htm. This version will scan any website / web application for XSS vulnerabilities and it will also reveal all the essential information related to it, such as the vulnerability location and remediation techniques. Scanning for XSS is normally a quick exercise (depending on the size of the web-site).

Later In The Series
This series will go on to look at SQL databases, and protecting against SQL injection attacks, as well as file operations and session management, including a look at one of the features of PHP designed to increase security and avoid PHP hack attacks- the PHP Safe Mode.

Leave a comment »

Site Loading Time

I was coding a web page which is over 600 lines of PHP codes. I was wondering how many seconds the server would take to load the web page. Because there are lot of control structures and loops to be executed.

How I achieved the need simply is described below.

Add the following code snippet to the PHP file(the line before the <html> tag starts).

$startTime = microtime();
$startArray = explode(" ", $startTime);
$startTime = $startArray[1] + $startArray[0];

Add the following code snippet to the PHP file(as soon the </html> tag was closed).

$endTime = microtime();
$endArray = explode(" ", $endTime);
$endTime = $endArray[1] + $endArray[0];
$totalTimeTaken = $endTime - $startTime;
$totalTimeTaken = round($totalTimeTaken,10);
echo "Load Time: ";
printf ("%f\n", $totalTimeTaken);

The method is simple what it does is store the time in micro seconds and get the difference when the <html> tag is printed and the </html> tag is printed. The differnence is the time required to load the page. Actually the correct word is  “Total Time taken to render the page”

Stupid and Simple.

Leave a comment »

PHP approach to Magic Constants

In general Magic constant is the sum of the  series of numbers that are in Magic Squares. But in programming also it is possible to find Magic Constants as well.

However in PHP also magic constants are popular, in general they are like global predefined constants. The interesting fact here is, those constants are available due to execution of a script or scripts based on the place they have been called. Those are very useful and magically help and make the developers life easier.

If you are from C++ then this is not a new concept to you.

Following are magic constants and I tried to give an example to show how those constants are used in the script.

All the magic constants starts with __ (double underscores) and ends with __ (double underscores).

__LINE__

This gives the current line number where this magic constant is.

<?PHP
//__LINE__ magic constant
echo "The line number is ".__LINE__." .";
?>

__LINE__ is more important in the DEBUG mode.

__FUNCTION__

This returns the name of the function where the __FUNCTION__ is put inside.

<?PHP
echo "Show me the function I use\n";
echo showMyName();
function showMyName(){
$functionaName=__FUNCTION__;
return $functionaName;
}
?>

__FILE__

This returns the file name of the file name including the full path.

<?PHP
echo "The file path :  ".__FILE__;
?>

Above are the important magic constants that can be used frequently in your code. If you are into creative thinking you can find various ways to get the real benefit of those.

Leave a comment »