25 PHP Form Validation Snippets

Recently i have involve myself in another application development. Regular Hungred Dot Com visitors will notice that the site currently offer advertisement space through this form. But really, we as a developers are always looking for such snippets or writing them out from scratch every single time regardless of how many time we know we have store it somewhere in our laptop! Man, its really frustrating searching on Google and find all sort of solution and trying to figure out whether the regular expression implemented is expensive or complete. So i came out with an idea to ease my life a bit and other developers by putting up an article such as this for my/our references. (This can be made into a class if you like to)

Validate Email

We can perform an email validation through this function.

	function isValidEmail($email){
		return eregi('^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$', $email);
	}

After fainted for a few seconds when i saw unreal4u finding, i decided to throw up preg_match solution instead.

	function isValidEmail($email){
		return preg_match('/^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$/i', $email);
	}

PHP 5.2 and above.

function fnValidateEmail($email)
{
  return filter_var($email, FILTER_VALIDATE_EMAIL);
}

Sanitize Email

We can further sanitize our email to ensure that everything is alright.

function fnSanitizeEmaill($string) {
     return  preg_replace( '((?:\n|\r|\t|%0A|%0D|%08|%09)+)i' , '', $string );
}

PHP 5.2 and above.

function fnSanitizeEmaill($url)
{
  return filter_var($url, FILTER_SANITIZE_EMAIL);
}

Validate Email Exist

This is not possible but certain validation can be use to validate email existence.

function check_email($email)
{
	$email_error = false;
	$Email = htmlspecialchars(stripslashes(strip_tags(trim($email)))); //parse unnecessary characters to prevent exploits
	if ($Email == '') { email_error = true; }
	elseif (!eregi('^([a-zA-Z0-9._-])+@([a-zA-Z0-9._-])+\.([a-zA-Z0-9._-])([a-zA-Z0-9._-])+', $Email)) { email_error = true; }
	else {
	list($Email, $domain) = split('@', $Email, 2);
		if (! checkdnsrr($domain, 'MX')) { email_error = true; }
		else {
		$array = array($Email, $domain);
		$Email = implode('@', $array);
		}
	}

	if (email_error) { return false; } else{return true;}
}

Validate Number Only

We can use PHP built-in function to validate whether a given value is a number.

function fnValidateNumber($value)
{
	#is_ double($value);
	#is_ float($value);
	#is_ int($value);
	#is_ integer($value);
	return is_numeric($value);
}

PHP 5.2 and above.

function fnValidateNumber($value)
{
	#return filter_var($value, FILTER_VALIDATE_FLOAT); // float
	return filter_var($value, FILTER_VALIDATE_INT); # int
}

Sanitize Number

We can force all value to be only numeric by sanitize them.

function fnSanitizeNumber($str)
{
	#letters and space only
	return preg_match('/[^0-9]/', '', $str);
}

PHP 5.2 and above.

function fnSanitizeNumber($value)
{
	#return filter_var($value, FILTER_SANITIZE_NUMBER_FLOAT); // float
	return filter_var($value, FILTER_SANITIZE_NUMBER_INT); # int
}

Validate String Only

Sometimes to validate name we can use this function to restrict only letters and spaces.

function fnValidateStringr($str)
{
	#letters and space only
	return preg_match('/^[A-Za-z\s ]+$/', $str);
}

Sanitize String

We can sanitize it instead of validate user input.

function fnSanitizeStringr($str)
{
	#letters and space only
	return preg_replace('/[^A-Za-z\s ]/', '', $str);
}

PHP 5.2 and above. built-in function by PHP provides a much more powerful sanitize capability.

function fnSanitizeStringr($str)
{
	return filter_var($str, FILTER_SANITIZE_STRIPPED); # only 'String' is allowed eg. '<br>HELLO</br>' => 'HELLO'
}

Validate Alphanumeric Characters

This validates alphanumeric characters.

function fnValidateAlphanumeric($string)
{
	return ctype_alnum ($string);
}

Sanitize Alphanumeric Characters

This sanitize alphanumeric characters. eg. "HELLO! Do we have 90 idiots running around here?" => "HELLO Do we have 90 idiots running around here"

function fnSanitizeAlphanumeric($string)
{
	return preg_replace('/[^a-zA-Z0-9]/', '', $string);
}

Validate URL Exist

This function will check whether a given URL exist and not only validate it.

	function url_exist($url)
	{
		$url = @parse_url($url);

		if (!$url)
		{
			return false;
		}

		$url = array_map('trim', $url);
		$url['port'] = (!isset($url['port'])) ? 80 : (int)$url['port'];
		$path = (isset($url['path'])) ? $url['path'] : '';

		if ($path == '')
		{
			$path = '/';
		}

		$path .= (isset($url['query'])) ? '?$url[query]' : '';

		if (isset($url['host']) AND $url['host'] != @gethostbyname($url['host']))
		{
			if (PHP_VERSION >= 5)
			{
				$headers = @get_headers('$url[scheme]://$url[host]:$url[port]$path');
			}
			else
			{
				$fp = fsockopen($url['host'], $url['port'], $errno, $errstr, 30);

				if (!$fp)
				{
					return false;
				}
				fputs($fp, 'HEAD $path HTTP/1.1\r\nHost: $url[host]\r\n\r\n');
				$headers = fread($fp, 4096);
				fclose($fp);
			}
			$headers = (is_array($headers)) ? implode('\n', $headers) : $headers;
			return (bool)preg_match('#^HTTP/.*\s+[(200|301|302)]+\s#i', $headers);
		}
		return false;
	}

Validate URL Format

This function will validate a given url to ensure the format is correct.

function fnValidateUrl($url){
return preg_match('/^(http(s?):\/\/|ftp:\/\/{1})((\w+\.){1,})\w{2,}$/i', $url);
}

PHP 5.2 and above.

function fnValidateUrl($url)
{
  return filter_var($url, FILTER_VALIDATE_URL);
}

Sanitize URL

PHP 5.2 and above.

function fnSanitizeUrl($url)
{
  return filter_var($url, FILTER_SANITIZE_URL);
}

Validate Image Exist

This function will check whether a given image link exist and not only validate it.

	function image_exist($url) {
	if(@file_get_contents($url,0,NULL,0,1)){return 1;}else{ return 0;}
	}

Validate IP Address

This function will validate an IP address.

function fnValidateIP($IP){
	return preg_match('/^(([1-9]?[0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5]).){3}([1-9]?[0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])$/',$IP)
}

PHP 5 and above. This can also specific validation for IPV4 or IPV6.

function fnValidateIP($ip)
{
  return filter_var($ip, FILTER_VALIDATE_IP);
}

Validate Proxy

This function will let us detect proxy visitors even those that are behind anonymous proxy.

function fnValidateProxy(){
	if ($_SERVER['HTTP_X_FORWARDED_FOR']
	   || $_SERVER['HTTP_X_FORWARDED']
	   || $_SERVER['HTTP_FORWARDED_FOR']
	   || $_SERVER['HTTP_VIA']
	   || in_array($_SERVER['REMOTE_PORT'], array(8080,80,6588,8000,3128,553,554))
	   || @fsockopen($_SERVER['REMOTE_ADDR'], 80, $errno, $errstr, 30))
	{
		exit('Proxy detected');
	}
}

Validate Username

Before we validate whether a given username is matches the one in our database, we can perform a validation check first to prevent any unnecessary SQL call.

function fnValidateUsername($username){
	#alphabet, digit, @, _ and . are allow. Minimum 6 character. Maximum 50 characters (email address may be more)
	return preg_match('/^[a-zA-Z\d_@.]{6,50}$/i', $username);
}

Validate Strong Password

Another good thing is to validate whether a particular password given by the user is strong enough. You can do that using this function which required the password to have a minimum of 8 characters, at least 1 uppercase, 1 lowercase and 1 number.

function fnValidatePassword($password){
	#must contain 8 characters, 1 uppercase, 1 lowercase and 1 number
	return preg_match('/^(?=^.{8,}$)((?=.*[A-Za-z0-9])(?=.*[A-Z])(?=.*[a-z]))^.*$/', $password);
}

Validate US Phone Number

This function will validate US phone number for US users.

function fnValidateUSPhone($phoneNo){
	return preg_match('/\(?\d{3}\)?[-\s.]?\d{3}[-\s.]\d{4}/x', $phoneNo);
}

Validate US Postal Code

This function validate US postal code.

function fnValidateUSPostal($postalcode){
	#eg. 92345-3214
	return preg_match('/^([0-9]{5})(-[0-9]{4})?$/i',$postalcode);
}

Validate US Social Security Numbers

This function validate US Social Security Numbers.

function fnValidateUSSocialSecurityCode($ssb){
	#eg. 531-63-5334
	return preg_match('/^[\d]{3}-[\d]{2}-[\d]{4}$/',$ssn);
}

Validate Credit Card

This function validate credit card format.

function fnValidateCreditCard($cc){
	#eg. 718486746312031
	return preg_match('/^(?:4[0-9]{12}(?:[0-9]{3})?|5[1-5][0-9]{14}|6011[0-9]{12}|3(?:0[0-5]|[68][0-9])[0-9]{11}|3[47][0-9]{13})$/', $cc);
}

Validate Date

This is a date format MM-DD-YYYY or MM-DD-YY validation which validate from year 0000-9999.

function fnValidateDate($date){
	#05/12/2109
	#05-12-0009
	#05.12.9909
	#05.12.99
	return preg_match('/^((0?[1-9]|1[012])[- /.](0?[1-9]|[12][0-9]|3[01])[- /.][0-9]?[0-9]?[0-9]{2})*$/', $date);
}

This is a date format YYYY-DD-MM or YY-MM-DD validation which validate from year 0000-9999.

function fnValidateDate($date){
	#2009/12/11
	#2009-12-11
	#2009.12.11
	#09.12.11
	return preg_match('#^([0-9]?[0-9]?[0-9]{2}[- /.](0?[1-9]|1[012])[- /.](0?[1-9]|[12][0-9]|3[01]))*$#'', $date);
}

Validate Hexadecimal Colors

This is a good validation for people who allows their user to change color in their system.

function fnValidateColor($color){
	#CCC
	#CCCCC
	#FFFFF
	return preg_match('/^#(?:(?:[a-f0-9]{3}){1,2})$/i', $color);
}

Make Query Safe

This function help sanitize our data to be SQL injection safe.

function _clean($str){
return is_array($str) ? array_map('_clean', $str) : str_replace('\\', '\\\\', htmlspecialchars((get_magic_quotes_gpc() ? stripslashes($str) : $str), ENT_QUOTES));
}

//usage call it somewhere in beginning of your script
_clean($_POST);
_clean($_GET);
_clean($_REQUEST);// and so on..

Make Data Safe

This function help to keep us protected against XSS, JS and SQL injection by removing tags.

function _clean($str){
return is_array($str) ? array_map('_clean', $str) : str_replace('\\', '\\\\', strip_tags(trim(htmlspecialchars((get_magic_quotes_gpc() ? stripslashes($str) : $str), ENT_QUOTES))));
}

//usage call it somewhere in beginning of your script
_clean($_POST);
_clean($_GET);
_clean($_REQUEST);// and so on..

Summary

A paranoid way to perform a form validation would be to validate first then sanitize your values for precautions. If you think the above snippets were suck or you have any good or awesome snippets to share. Please throw your comment and share with us!

10 PHP Micro Optimization Tips

There are many ways to improve the way you write your PHP code. And we can easily increase the efficiency of our code just by putting in some effort during development. However, there might be some unknown information that you might not aware in PHP that can help improve your code. In this article, i will try to provide you with some tips that can serve as micro optimization for your code and could also add on to the list of knowledge that you have in PHP. We will also look at many benchmarking of these tips where possible!

Loop

Every program will required certain amount of loop. And loop is considered as efficiency killer if you have many nested loop (means loop in a loop) as one loop will required to run 'n' times and if you have 1 nested loop, this means your program will have to run n2 times. Well, i think you can do the math. But we are not talking about this. There is something more interesting about loop in PHP. There are many ways we can define a loop in PHP. But how do you know which one is the best way to loop your data? Apparently, using a for loop is better than foreach and while loop if the maximum loop is pre-calculated outside the for loop! What do i mean? Basically is this.

#Worst than foreach and while loop
for($i =0; $i < count($array);$i++){
echo 'This is bad, my friend';
}

#Better than foreach and while loop
$total = (int)count($array);
for($i =0; $i < $total;$i++){
echo 'This is great, my friend';
}

The above shows two different ways of writing a for loop. The first way includes the operation count into the loop while the second one pre-calculate the total number of loop outside it. The difference between these two is that the second doesn't run count operation n times while the first one did. You can find this VERY interesting benchmarking on loops on  PHP.

Single Vs Double Quotes

Since i mentioned that benchmarking page on loops, it also includes the benchmark for single(') and double(") quotes. Now, between these two what is the best one to use? It really doesn't makes much differences. But i preferred to use  single(') quote because i don't have to press shift? Just kidding (not). That's one of the reason why i use a single quote over the double one. But the other reason is that PHP will scan through double quote strings for any PHP variables (additional operation) and usually i don't mix my variables and strings into one. I usually use single quote instead. However, you might also have aware that if an empty string is declared using a single quote, it seems like there is a performance pitfall. You or I might want to take note of that. Basically, there is a dollar($) symbols in your string, try to avoid double quote unless its variable?

Pre increment vs Post increment

Well, increment a certain value also have a few ways to improve. We all know that there are many ways to increment integer values such as

$i++;
$++i
$i+=1;
$i = $i + 1;

Out of all these what way is the most efficient? In PHP, it seems like pre increment is better than the other ways of performing an increment. Its around 10% better than post increment? The reason? Some said that post increment made certain copy unlike pre increment. There isn't any benchmark done for PHP but i found one on C++ which should be quite the same. Well, without a proper benchmark on this, i can't really confirm this. Furthermore, it really doesn't makes a big differences towards normal programmers but may affect those who are working towards micro optimization.  Nonetheless, many people do suggest pre over post increment in term of optimization.

Absolute Path VS Relative Path

Absolute path which is also known as full path compare to a relative path which will be better for PHP? Surprisingly, it seems that absolute path is better. Compare to relative path which might just help to screw up your include and require operation in PHP, absolute path doesn't. Well, that's the reason why i use absolute path. But the real reason is that using absolute path eliminate the need for the server to resolve the path for you. Simply to say, do you know where the file is located when you just look at a relative path or is it faster if i just throw you the full path?

Echo Vs Print

Yes! I know, echo is better. But how much better? Interested to know? I am interested. So i went to dig a bit on the internet and found some useful information for benchmarking between these two! Its around 12%-20% faster using echo compare to print when there is no $ symbol in the printing string. And around 40-80% faster if there is an $ symbol used in a printing string! This really demonstrate the differences between the keyword $ symbol used in PHP.

Dot Vs Commas Concatenation

Between dot and commas which way do you use to concatenate between two strings/variables? I personally used dot to concatenate my stuff. Such as the one shown below

$a = '10 PHP programming ';
$b = 'Improvement Tips';
#10 PHP Programming Improvement Tips
echo $a.$b;

I usually do the above. Instead of this,

$a = '10 PHP programming ';
$b = 'Improvement Tips';
#10 PHP Programming Improvement Tips
echo $a,$b;

Well, between these two which is more efficient? If you did visit the link for benchmarking between echo and print, you might have aware on the exact same test, they also have performed test case for dot and commas. The result shows that dot is more preferable if there are no variables or $ symbol involved which is around 200% faster. On the other hand, commas will help to increase around 20%-35% efficiency when dealing with $ symbols.

str_replace vs preg_replace vs ereg_replace

Ok! We have 3 string search function in PHP. Out of these three functions, which do you think will run the fastest? Some of you might have know, str_replace will run faster. Reason? str_replace doesn't run any complex expression unlike preg_replace and ereg_replace. Well, maybe many of you might know that but it is not necessary always str_replace that runs fastest. If you have to call str_replace 5 times compare to preg_replace, which will run faster? (str_replace, of course) Wrong! preg_replace runs 86.99% faster than 5 str_replace function call! Basically, i also have such doubt and search for such benchmark. The benchmark really explains some doubts we have in these functions.

Find Timestamp

When you want to find out the time when your script starts running in order to get that timestamp to store it into your database. The first thing you do is to fire up your Google and search for some PHP function. Well, after PHP5 you do not have to do that. After PHP 5 you can easily retrieve the execution timestamp of your script by using

$_SERVER['REQUEST_TIME']

This could really save some time digging for something that already exist within your reach.

explode Vs preg_split

Well, when you want to split a string what do you use in PHP? I usually used explode because it support even PHP4.0 and that's also what i was taught by my ex-colleagues. The answer in term of efficiency is explode. Split supports regular express and this makes it quite the same comparison between str_replace and preg_replace, anything that have regular expression support will usually be a bit more slower than those that doesn't support it. It took around 20.563% faster using explode in PHP.

Other Benchmarks

I believe this list can go on forever with such great benchmarking site i found. It basically shows you most of the benchmarking between PHP functions or those articles that claim whatever stuff is better than the other in PHP but doesn't provide you with any real evidence on their article. In this article, hopefully i have provided you with the necessary information for you to perform some micro optimization and also other more of such optimization through the benchmarking site.

Summary

I believe many of you have see all these information floating around the internet. But the only differences i see is that they don't really provides you with the real interesting part of this article, that is the benchmark of each test. This article really help me a lot with all the figures and testing given by all these great benchmarking site. Hopefully it also gives you the same result.

P.S: Most of these benchmark sites are run on real-time.

Integrate Paypal Express Checkout Solution

As a web developer, there will surely be someday where you wish to integrate Paypal into one of your products or services. The most appropriate way is to read the documentation provided by Paypal. But reading it doesn't mean you will understand the documentation with one shot and this call for a lot of research and finding before your Paypal will work. I went through this process these few days that is why there wasn't much article written in the process.  Although it wasn't really difficult but going through the process of reading first before looking into their sample codes really wasn't the correct way of approaching this solution. Instead, looking into the sample code will definitely brings light to integrating Paypal express checkout solution (well, you still have to read a bit). In this article, i will try to demonstrate Paypal express checkout solution as simple as possible for you guys to be able to DIY.

Paypal Express Checkout

What is Paypal Express checkout solution? Paypal Express Checkout makes it easier for your customers to pay and allows you to accept PayPal while retaining control of the buyer and overall checkout flow. This means that you can integrate a payment solution with Paypal that retain most of the interaction on your website other than user login and verifying the product they are purchasing. Paypal express checkout also provides you with the ability to create recurring payment which can really eliminate the need to repurchase the exact service or product every single time. However, Paypal express checkout solution doesn't have the ability to allow your user to use credit card for purchases. Your customers must have Paypal in order to purchase with this solution. Credit card solution will only be available together with Paypal in Website Payment Pro solution. Hopefully this clear some doubt and help you select what solution you really need.

Integrate Paypal Express Checkout Solution - Step 1

Firstly, you might wonder where exactly are the correct documentation out of all the places in Paypal. You can get the documentation and Sample at the respective links. The sample is contain at the section PayPal API: Name-Value Pair Interface as i believe this will give you a better understanding on the flow of Paypal express check out solution. The sample files will required you to throw them  into your server and run (go to the browser and key in the url you have thrown the folder into) as it will simulate some of the payment flow you might want. Then you will look into the code and see how they are achieved. Please take note that localhost might not work for you as it will required you to have curl installed.

Integrate Paypal Express Checkout Solution - Step 2

Once the sample are placed into your server and you have play around, the next thing you might wonder is the exact file you will required to run your own Paypal express checkout solution. And here are the files you will only need.

  • APIError - display error
  • CallerService - main player that initial the talk
  • constants - all the required variables
  • SetExpressCheckout - display for step 1 of the process
  • GetExpressCheckoutDetails - display for step 2 of the process
  • DoExpressCheckoutPayment -  display for step 3 of the process + send final request to paypal
  • ReviewOrder - request handler for step 1 and responsible to redirect to step 2

The files i am looking at are all PHP files.  Well, the above file respective function should be self explained. The first 3 files(APIError, CallerService and Constants) are the files imported into the ReviewOrder and  DoExpressCheckoutPayment files as they are required to talk to Paypal. Once we understand this it is time to go into a more complicated stuff.

Integrate Paypal Express Checkout Solution - Step 3

To illustrate what is going on in the sample file, we will look at the following diagram provided by Paypal.

From left to right, we have 5 interfaces user will see. And two of them are display from Paypal where it is colored in blue (2nd and 3rd interface). Hence, we left with 3 interfaces which are SetExpressCheckout, GetExpressCheckoutDetails and DoExpressCheckoutPayment which is 1st, 4th and 5th interface respectively.  So we are all clear with the display files right now. Next we will need to know where ReviewOrder will appear. There are altogether 4 Calcuts as written on the diagram. The ReviewOrder will be triggered on the 2nd and 3rd Calcuts where SetExpressCheckout API and GETExpressCheckoutDetails API is being fired. Don't worry about what does these API means at the moment. Just treat them as a method that will tell Paypal what they do.

Integrate Paypal Express Checkout Solution - Step 4

I guess everyone should understand how Paypal work looking at the sample file and the explanation above.  Next i will explain some of the important things you will need to know since writing all the codes here is meaningless as they are the same for every sample files. It just makes it more confusing to read. Firstly, for each request made to Paypal, you will always see the following line in the sample file.

$resArray=hash_call("SetExpressCheckout",$nvpstr);

where $nvpstr is the name-value pair string passed into the method hash_call. What this function hash_call does it to send the request to Paypal to notify them the action you performing. In this case, SetExpressCheckout API is being performed here. There are also other API as mention previous such as GetExpressCheckoutDetails API and DoExpressCheckoutPayment API. These are the three API you will need to talk to Paypal in each stage shown on the previous diagram. So we should all clear about what does API mean that are written all over the Paypal documentation. The next important step is to know what name-value pair does each API required you to send in order for Paypal to understand you.

Integrate Paypal Express Checkout Solution - Step 5

Here we will see what does each API in the process of express checkout required. For SetExpressCheckout, you will required to have the following name-value pair in your string.

  • AMT
  • CURRENCYCODE
  • RETURNURL
  • CANCELURL
  • PAYMENTACTION

That is all! But in the sample it gives you more than just the above which is pretty good to understand what can be dump into the nvp string for it to display what you want on the paypal website where your user gets redirected.

For GetExpressCheckoutDetails API is pretty simple. It will just required you to have a token passed into the nvp string and this token can be retrieved via $_GET method where Paypal send it through there.

Lastly, for DoExpressCheckoutPayment API, you will need to provide the following nvp for it to work.

  • TOKEN
  • PAYERID
  • AMT
  • CURRENCYCODE
  • PAYMENTACTION

And that's it! The value forGetExpressCheckoutDetails and DoExpressCheckoutPayment API are provided by Paypal during the process while SetExpressCheckout data are given by you.

Summary

I believe the above explanations were pretty clear. But i still used quite a hell lots of time working on it *SLAP MYSELF*! This article is intended to provide any newbie on Paypal to get the hang of integrating Paypal without the need to spend time on reading and learning all about Paypal integration. However, the sample provided by Paypal is not secure and is only used to serve as a demonstration on 'how integration can be made easy'. I believe this article will be pretty useful for anyone to understand how Paypal work rather than reading few thousand words given by Paypal and never direct you to the correct sources or code (other than more documentation). Guess what? I found this Paypal Integration Wizard which is a wizard that creates all the above codes for you! :[

Enhance Security Hash Function For Web Development

Previously i wrote an article on Better Hashing Password in PHP and PHP Secure Login Tips And Tricks. Both these articles are closely link to hash function and i find that i really didn't answer hash function on these two articles clearly enough. Especially on the article Better Hashing Password in PHP where i find my reader get confused on some of the security term used and caused some misunderstanding on the article. Hence, i came up with an idea to write out an article to detail some hash function question and improvement any developer can make to further secure their website. You will get a better understanding on security hash function and apply it on your web development once this is over.

Stop Using MD5 or SHA-1 in the future

If you have read Better Hashing Password in PHP, US-CERT of the U. S. Department of Homeland Security said that MD5 should be considered cryptographically broken and unsuitable for further use in 2008. Wiki explained a good detail of MD5 vulnerability that will surely make you switch your hash function from md5 to other better hash function out there. SHA1 on the other hand is more secure than MD5. However, collision has also been found on SHA-1. This is no surprise as both SHA-1 and MD5 are descended from MD4. Nonetheless, SHA-1 is still strong enough currently but not in the future looking at how computer power advancement has been progressing. Furthermore, faster way of creating a collision has also been found with only 252 attempt required which is a significant reduction from 263. What does this means? This means that SHA-1 attacks affect collision resistance, not pre-image resistance. Short to say that after 252 operations, the researchers are able to generate two unique messages that hash to the same digest value which is approximately a few month times in a dedicated hardware to construct such collision. While obtaining a SHA-1 collision via brute force would still require 280 operations. By the way for people who have no clue what's SHA means, it stand for Secure Hash Algorithm which is required by law for use in certain U. S. Government applications, including use within other cryptographic algorithms and protocols, for the protection of sensitive unclassified information. Thus, SHA family algorithm should be pretty solid for anyone who wish to secure their web system unless weakness has been found such as SHA-1.

Why Collision Is Bad

Any hash function will face collision eventually due to pigeonhole principle whenever members of a very large set are mapped to a relatively short bit string. The impact of collisions of any kind are undesirable. This means that two different set of message may generate the same hash value and one hash value may be generated by more than one message. Simply to say that the hash function doesn't generate a one to one relationship hash value. What this means for security is that there is a message exist 'n' which is different from 'm' that can be used to access the same system. Therefore, the more collision resistance a hash function is the better it is for security. Let me provide you with an example on how bad collision can caused for a system. Assume  a system had their hashed password compromised. Instead of 'hello' as password, another value 'bye' which was generate the same hashed value (which is not true) that the hacker is able to use access the system. Now, instead of a 5 length word, a similar hash value can be found with a 3 length word. And this means shorter time to crack your hashed value and easily it is for our hacker but its not always necessary this case. Obviously this is just an example and security cautious people will definitely do much more than this to prevent birthday or brute force attacks.

Moving To SHA-2 Hash Function

Like i mention on Better Hashing Password in PHP it is time to start considering moving towards a more solid hash function that have not found any weakness yet. Most U.S. government applications will be required to move to the SHA-2 family such as SHA-224, SHA-256, SHA-384, and SHA-512 of hash functions by 2010 as stated by NIST(National Institutes of Standards and Technology) on their hash function policy. Hence, for web security conscious people, we should also start moving towards SHA-2 too. Currently, PHP 5.12 also offered such option, hash

$phrase = 'This is my password';
$sha1a =  base64_encode(sha1($phrase));
$sha1b =  hash(’sha1′,$phrase);
$sha256= hash(’sha256′,$phrase);
$sha384= hash(’sha384′,$phrase);
$sha512= hash(’sha512′,$phrase);

For users who used version lower than PHP5.12, you you can try to use mhash which is an open source class for PHP.

$phrase = 'This is my password';
$sha1a =  base64_encode(sha1($phrase));
$sha1b =  base64_encode(bin2hex(mhash(MHASH_SHA1,$phrase)));
$sha256= base64_encode(bin2hex(mhash(MHASH_SHA256,$phrase)));
$sha384= base64_encode(bin2hex(mhash(MHASH_SHA384,$phrase)));
$sha512= base64_encode(bin2hex(mhash(MHASH_SHA512,$phrase)));

SHA-2 should be used if you are web security minded person. SHA-1 can still be used definitely but additional enhancement would have to be in placed to strengthen such hash function from various attacks on its weakness. On the other hand, you may want to avoid MD5 for very security data.

Is SHA-2 Totally Secure?

Like we mention previously, all hash function is unavoidable towards collision. It is the same as stating that any system can be compromised with the proper amount of time and resources. The objective of a hash function is not to provide a totally uncrackable solution but to delay the process of breaking it where the process might required few hundred year to achieve.

Currently, the best public attacks on SHA-2 break 24 of the 64 or 80 rounds where 64 and 80 rounds is the number of loop in SHA-256 and SHA-512 respectively. Hence, it is safe to say no collision has yet to be found on SHA2 family yet. Hence, SHA-2 family can be said to have high collision resistance at the moment.

Attacks On Hash Function

An attack can be process faster with the given resources.  Some ways is to divide up the cracking process to different computer or exploit CPU architecture to take advantage of multiple cores on one processor or multiple processors on a single machine. This makes cracking the password much easier. And the below attacks might just be one of the cracking process used by them.

Birthday Attack

Most attacks on hash function are targeting the hash function collision resistance part as it is easier to launch a collision attacks. At the same time, preimage attacks has yet to be found on established hash functions.  The typical kind of attack against hash function will usually be collision attacks which is also known as birthday attacks. We mention earlier that every hash function will face collision problem. Therefore, theoretically it is possible to find two message that produce the same hash value.

The birthday attack is a statistical probability problem. The method used to find a collision is to simply evaluate the function ƒ for different input values that may be chosen randomly or pseudorandomly until the same result is found more than once. Because of the birthday problem, this method can be rather efficient.

Let's see how efficient it is. Given 'n' inputs and 'k' possible outputs, there are n(n-1)/2 pairs of inputs. For each pair, there is a probability of 1/k of both inputs producing the same output key. So, if you take k/2 pairs, the probability will be 50% that a matching pair will be found. If n is greater than sqrt(k), there is a good chance of finding a collision.

Brute Force Attack

brute force attack is the most fundamental attack but is often used.  Brute force is often used against hash value as hash function generates a one way hash value. This also means that the hash value is irreversible which makes it such a secure function. The only bet is to try each and every words in order to get it right. However, such method is very time consuming as the search space may be very huge.

Rainbow Table Attack

Another common attack is to use a rainbow table to try to figure out the original message given a hash value. Unlike brute force that attempt to match every single  character, rainbow table attack uses tables which offer time-memory-trade-off  and chains to lookup for the particular message. The table content does not depend on the hash value to be inverted. It is created once and then repeatedly used for the lookups unmodified. Increasing the length of the chain decreases the size of the table. It also increases the time required to perform lookups, and this is the time-memory trade-off of the rainbow table. In a simple case of one-item chains, the lookup is very fast, but the table is very big. Once chains get longer, the lookup slows down, but the table size goes down. The table here refers to the rainbow table where all kind of password is being hashed and stored in it. This process usually takes a while as the table should be extremely large to have a possibility of finding hash and as stated in bold above, it is usually repeatedly used for lookups unmodified. Once you understand this, you can visit kestas for an explanation of how rainbow table attack works.

Defensive Strategies

There are known ways of attacks for hash function. Similarly, there will be defensive strategies web developers can apply to better protect our system.

Using SALT

Another common way of enhancing hash function is through the using of SALT. A salt is used to strengthen user password if ever the system table is to be compromise. SALT is just an additional string appended to the password before it is being hashed and store into the database table. The same exact SALT will be required during verification between the user entered password and stored password. However, some of us get confuse of the capability of a SALT in cryptography can greatly help in a web system.

Before i explain SALT criteria, let's see what SALT can do for us. If your system database was compromised but no SALT was used for your password hashing. What will you do? Basically you will send an email out to everyone and request them to change their password like what Reddit did (well, the only differences is they did not even hash their password). On the other hand, if SALT is being used in this case, you guys will just have to modify the SALT algorithm without causing so much kiosk. Furthermore, the passwords that was compromised will be pretty solid to be easily decrypted.

Let’s look at brute force attack. We assume the hacker know the length of your SALT (since its compromised) but you did not change the length (assume the length is 1000 character). The hacker began to hack your system using the passwords they receive. Let’s assume there are around 94 character you can fill for your SALT or password (Its around 94 characters, please refer to ASCII values). Hence, 1 single character will make a brute force run 92 times to get a shot of a single character password (means no salt). Now, we have 1000 character for our SALT. This means that our hacker will have to try 921000 to get a shot to decrypt one password on the list of hacked passwords. This means they will have to try 101500 which is many many combination for just one password! I don’t think one year is enough for them to crack one password using a single computer. But correct me if i’m wrong. Anyway we can see from this interesting table from Lockdown.co.uk - The Home Computer Security Centre research which was written on Friday 10th July 2009 04:01 that the longer and more character in a password, the longer it will need to crack in a simple brute force attack. Try imagine 1000 character with different combination will take after looking at the table.

Next, let’s look at rainbow table attack attempt to crack such password. Now, we understand that rainbow table precompute hash chain. The goal is to precompute a data structure that, given any output h of the hash function, can either locate the p in P such that H(p) = h, or determine that there is no such p in P. Since all our password are salted uniquely, the attacker will have to generate a rainbow table for each salt for each possible password – exponentially increasing the effort an attacker must make. Furthermore, looking at the size of the SALT, it is infeasible for such attack to occur because of the sizable investment in computing processing, rainbow tables beyond fourteen places in length are not yet common. So, choosing a password that is longer than fourteen characters or that contains non-alphanumeric symbols may force an attacker to resort to brute-force methods.

However, OUR TABLE WAS COMPROMISED! This doesn't mean our system is compromised as well. It really depend on the SALT function you create as mention on Better Hashing Password in PHP. A paranoid SALT implementation criteria might have:

  • More than 64 bits long of SALT where 64 bits is the least amount of SALT length required to be secure as specific in PKCS #5
  • Randomly populated ASCII value for each SALT character
  • Validate the SALT to ensure it contains symbols, uppercase, lowercase and numbers
  • BASE64_encode it before storing into database (decode it when used)
  • Use other dynamic field in the table that might change by users as part of the SALT such as email address, telephone numbers, last login
  • Validate that no such password hash exist on the table.

Basically the above criteria should be enough for very solid SALT implementation that will not compromised your system even if your database was compromised. Let me explain the reason why on the above criteria.

  • Longer salt length means more brute force values and bigger size rainbow table required
  • ensure that any kind of character is being considered as salt to generate different hash for each password.
  • this is just a validation to ensure every kind of salt is being purchased
  • decode this salt value into the database so that stupid hacker will use it directly.
  • this is the criteria that makes the system secure as we are not doing hash(password + salt) instead we utilize the data in the table or other table to hash it this way hash(password + salt + username + secret answer). Take note that the each variable used to create a hash value are all static data (it doesn't change). Hence, the hacker might not know how the sequence and data of hashing the password is generated unless the function of the SALT is also compromised which is possible (developers can be hackers). However, the above description wrote dynamic data. This means that the SALT function will always generate a new SALT or password to be updated to the table whenever the dynamic data changed. Since last login time will only change upon login, we will use this dynamic data and generate a hash using this sequence hash(password + salt + last login time). Hence, whenever a user logged in, a new password hashed is generated and update the password field (which is a hash).  During user validation we will use hash(password + salt + database last login time) and update current time and new password into the database upon logged in. Similar, SALT can be generated every time upon logged in as well. Hence, we will use a new salt for every single logged in request. Now, if a hacker compromise your database, unless it can crack before every user logged in, this is pretty solid i would said.
  • In case of collision, always validate that the hash value cannot be found within the table before inserting it.

Like i said, this is a total paranoid solution that some of you might like to have. But basic hash(password + salt + username + secret answer) will be quite enough to protect your system provided you follow the PKCS#5 way of constructing your salt. You may want to visit PHP Secure Login Tips And Tricks for login security.

Iterative Hashing Technique

One way of enhancing your hash function is through iterative hashing. This technique basically takes a particular hash function and rehashing it many times (around 1000-10,000) making it incredibly hard to crack which is also known as key stretching or key strengthening in cryptography. Assuming a hacker manage to crack a hash value within 8 hours, rehashing it many times might change this from 8 hours to 8000-80,000 hours per password. I think we can imagine how an attack will work on such technique where every decrypted hash resulted in more hash to be decrypt. Its like opening a birthday present and found yourself a new box to open again (make me cry). Now we all know that SHA family hash function are all considered as fast. However, SHA-2 family might run slower than SHA-1 hash function as the block size is bigger but no much differences is being made.

What most of us will worry about is the time required for that many iterative round hashing to occur each time a user login or account creation. This will depend on how secure your system is required. You don't expect a bank web portal to compromise security for speed don't you? (hacker: HELL YEAH! SPEED!! SPEED!!) Hence, you may want to tune this according to your need and be at least 1000 iterative as something between 2-100 iterative is equivalence to nothing as such hash might had already exist on rainbow table. On the other hand, according to Wiki, Slowest personal computers in use today (2009) can do about 65000 SHA-1 hashes in one second using compiled code. Thus a program that uses key strengthening can use 65000 rounds of hashes and delay the user for at most one second.  The standard as mention on PKCS #5 is around 1000 and above. And in case you never heard of PKCS, in cryptography, PKCS refers to a group of Public Key Cryptography Standards devised and published by RSA Security.

SALT can be appended to each iterative to make your iteration algorithm more secure but it really depends on how you are going to design this.

Is Double Hashing Better?

Double hashing here is different from iterative hashing. Double hashing uses two different hash function instead of one. This is really confusing as double hashing is also refer to iterative hashing by some people. Hence, making everything confusing. An example is


sha1(md5($pass))

your system is at least as weak as the weakest of the hash algorithms you are using (md5).  It is true that both iterative and double hashing will reduce the search space but the effective reduction is insignificant compare to the gain from the benefit of iterative hashing. On the other hand, double hashing is bad as it will weaken the system since the hacker will only required to break the weaker hash function. Therefore, try avoiding double hashing and go for iterative hashing instead. Furthermore,  hashing two times with the same algorithm is considered suboptimal.

References And Good Reading

Conclusion

Enhance Security Hash Function is a pretty interesting topic. Understanding the strength and weakness of your used hash function is necessary to better protect your web system. Hash function is the only method most of us, web developers and the internet are using to secure ourselves. Without fully understanding  hash function is like a man on a battle field  with a gun but have little to no understand of its capability and weakness. And that's bad. (not that gun where you bring along with you to the toilet)

PHP Secure Login Tips And Tricks

Every website on the internet faces a similar threat, hackers. Every single website can be a target of a hacker if security measures aren't implemented properly especially when it comes to login pages where our most sensitive data are being held. Hence, there is a need to better understand how well your login page has been implemented to be considered as really secure. In this article, you will get a list of PHP secure login tips and tricks that will definitely help you decide on your secure rating of your login page.

Length Of your username and password

Both your username and password should be at least 6-8 characters long. A longer combination of username or password will make brute force attack or any other password cracking algorithm longer to crack. This can really help your network administrator to detect an attack before the attack penetrates through your login page.

Encrypt your password

We all know that encryption is necessary in term of any password. But i would still like to stress such importance. We are very dependent on encryption algorithms such as MD5 or SHA-1. However, these two algorithms are no longer that secure as compared to the older days. On Wednesday, February 16, 2005 SHA-1 has been broken by three china researchers. Although it is more towards collision attack rather than pre-image one we can assure one thing is that SHA-1 can be broken. You can read more about it on Bruce Schneier article. On the other hand, you can find MANY MD5 cracker online nowadays through Google. eg. md5crack.com. But similarly they are all collision attacks.  Wiki explains MD5 vulnerability in a way you will be discouraged from using it. It is time to encrypt your users password using SHA-2 such as sha256, sha384, sha512 or better. If you are using PHP 5.12 or above, there is a new function, hash that supports SHA-2.

$phrase = 'This is my password';
$sha1a =  base64_encode(sha1($phrase));
$sha1b =  hash(’sha1′,$phrase);
$sha256= hash(’sha256′,$phrase);
$sha384= hash(’sha384′,$phrase);
$sha512= hash(’sha512′,$phrase);

For people who are using PHP 5.12 and below, you can try to use mhash which is an open source class for PHP.

$phrase = 'This is my password';
$sha1a =  base64_encode(sha1($phrase));
$sha1b =  base64_encode(bin2hex(mhash(MHASH_SHA1,$phrase)));
$sha256= base64_encode(bin2hex(mhash(MHASH_SHA256,$phrase)));
$sha384= base64_encode(bin2hex(mhash(MHASH_SHA384,$phrase)));
$sha512= base64_encode(bin2hex(mhash(MHASH_SHA512,$phrase)));

SHA-2 should be used to secure your future application. Although MD5 and SHA-1 can still be used for authentication purposes with a very secure password combination. eg. (eQ@xC#Eif2dsa!e2cX2?"}23{D@.

NOTE**: NEVER DOUBLE HASH!

Double hashing is *worse* security than a regular hash. What you’re actually doing is taking some input $passwd, converting it to a string of exactly 32 characters containing only the characters [0-9][A-F], and then hashing *that*. You have just *greatly* increased the odds of a hash collision (ie. the odds that I can guess a phrase that will hash to the same value as your password).

sha1(md5($pass)) makes even less sense, since you’re feeding in 128-bits of information to generate a 256-bit hash, so 50% of the resulting data is redundant. You have not increased security at all.

Credit goes to Ghogilee

****updated on 8 Oct 09

On the note of Ghogilee, i found a few errors which i would like to point out. Double hashing here is referring to two different hash function.  It does reduce the search space but doesn't *greatly* increased the odds of a hash collision.  On the other hand, SHA-1 should be a 160-bit hash not 256-bit and not only does this doesn't increased the security but also weaken the hash function as the hacker will only required to crack the weaker hash function in this case md5.

You may want to visit Better Hashing Password in PHP for more information. If you wish to understand the risk and stuff you can do with hash function, please visit Enhance Security Hash Function For Web Development. Here i document the most detail hash function i could for your information.

Enhance Hash With Salt

Once you have decide your secure password encryption algorithm, the last thing you might want is to have different user having the same encryption algorithm hash code. This can bring another problem of more than one account being compromised at the same time when there are multiple same hash and short password can easily be cracked with ease when your database and tables have been known. We can generate a salt in order to overcome this problem so that the string is longer and more random (providing that the salt + password are random enough).

define('SALT_LENGTH', 15);
function HashMe($phrase, &$salt = null)
{
$key = '!@#$%^&*()_+=-{}][;";/?<>.,';
    if ($salt == '')
    {
        $salt = substr(hash('sha512',uniqid(rand(), true).$key.microtime()), 0, SALT_LENGTH);
    }
    else
    {
        $salt = substr($salt, 0, SALT_LENGTH);
    }

    return hash('sha512',$salt . $key .  $phrase).$salt;
}

The above function contains two parameters. The first will take in a phrase and generate a SHA-2 salt if the second parameter is placed with an empty variable. However, if both parameters contain values, it will be used when you wish to compare between two hashes. We can use the above method this way,

$username = cleanMe($_POST('username'));
$password = cleanMe($_POST('password'));
$salt = '';
$hashed_password = HashMe($password, $salt);
$sqlquery = 'INSERT INTO  `usertable` ("username", "password", "salt") VALUES  ("'.$username.'", "'.<d>$hashed_password .'", "'.$salt.'") WHERE 1';
..

The above will insert the information into the table when user is being created. We will check the user with the following salt.

$username = cleanMe($_POST('username'));
$password = cleanMe($_POST('password'));
$salt = '';
$sqlquery = 'SELECT `salt`, `password` FROM  `usertable` WHERE `username` = "'.$username.'" limit 1';
..
#we get the data here and placed into variable $row
$salt = $row['salt'];
$hashed_password = HashMe($password, $salt);
if($hashed_password  == $row['password']){
#verified
}
else{
#ACCESS DENIAL
}
..

The objective of salt is to lengthen the password in the table and also create a totally random hash code for each password. Hence, even if your table is being compromised, it will really take a lot of time for them to crack those hashed password. (We are assuming login page already implemented protection against multiple false log in)

Do not use easy guess username for administrators

It is always wise to use a slightly more challenging username for any administrators on your system. Username like 'admin', 'root' or 'super' will surely be the one on the hacker list to determine any administrator username. Be smart! Use something more challenging such as 'iamtheking' as a username instead (if your login system is case insensitive).

Log user login attempt

It is actually wise to log every important event in a system. Definitely, login page is one of them. We can determine whether any attempt of attack on our system is being carry out with a proper logging system. The log file or table can be very useful to track back what had gone wrong during a specific time frame when an attack occurs to determine whether an attack was launched to determine whether the login page was compromised.

Handle Error

It is important to prevent any error from being displayed to malicious users. These information is very useful for them to determine how to break into your system. Hence, they will try any type of value in order to break your PHP functions. Therefore, an ampersat symbol (@) should be placed in front of any function to prevent an error from occuring. On the other hand, you can use the function mention on Solutions to SQL Injection Attack which uses die to generate a better SQL error message that can be both professional and at the same time log your errors. The function is shown below,

function sql_failure_handler($query, $error) {
	$msg = htmlspecialchars('Failed Query: {$query}<br>SQL Error: {$error}');
	error_log($msg, 3, '/home/site/logs/sql_error_log');
	if (defined(‘debug’)) {
		return $msg;
	}
	return 'An error occurs, please try again later.';
}

#query=test;DELETE FOM breakplease;
$query = 'SELECT * FROM user WHERE name ='. base64_decode($_GET['query']);
mysql_query('$query) or die(sql_failure_handler($query, mysql_error()));

Always filter user input

Remember on the articles Solutions to SQL Injection Attack and Solutions to Cross-Site Scripting (XSS) Attack which mention that filtering user input is very important as hackers will use any way to break your login system. The rule is to never TRUST your user input until every last verification gets through. You can use the following function in PHP for your filter assistance,

htmlentities()
strip_tags ()
utf8_decode ()
htmlspecialchars()
ctype_digit()
ctype_alnum()
stripslashes()
str_replace()

Be Innovative Not Informative

We must be innovative on the message we present to our users whenever an error or login fail occurs. Message such as 'invalid password' or 'invalid username' is bad practices that gives information to malicious user what they went wrong. Instead, provides something like 'Login Fail. Please try again' will be a much more appropriate approach.

USE LIMIT or WHERE 1

In SQL query, for any login attempt, always place a LIMIT 1 at the end of your SQL statement. If there is a chance where a successful SQL injection is performed, only one account is being compromised instead of all. On the other hand, using WHERE 1 can help prevent any additional SQL query from placing at the front of your where clause.

Check HTTP Referrer

The basic of every security check is to ensure that the HTTP referrer came from the form on your site. If the HTTP referrer is suspicious, reject the request immediately. Although, HTTP Referrer can be easily spoofed with JavaScript it is always good to have any form of protection on a login page. However, some firewalls or proxies strip this information out which will caused many of your users to be unable to login successfully. Hence, you might want to consider whether to implement such checking for your login system.

Nonce authentication

Another better way of authenticating than checking the HTTP Referrer is to use acryptographic nonce. A nonce is a number used once, and it is used for intention verification purposes. Think of it as a password for THAT particular form and only can be used once. It really depends on how you implement your Nonce between the client and server.

Use maxlength

It is definitely a great idea to only allow a maximum length of characters user can placed on an input box. This is like a restriction placing in front of malicious user to provoke their creativity in order to penetrate your system. However, you might not like this idea too as it minimize the number of combination for hackers to crack your login page. Personally i will place such restriction as my login page will never allow more than certain fail login.

$_POST ONLY

When dealing with any form data. The only answer is using $_POST. NO $_REQUEST or $_GET should be use as you are just making life easier for hacker and weaken your security. Although $_POST can still be used by hacker but it makes the job troublesome.

Sub String Not Trim

In a login page, it is best to secure ourselves. Hence, if a user made an error on their username or password, the system should not correct for them. If a user enters a username with leading or trailing space we are not going to trim it nicely for them before we check. On the other hand, we will sub string it out so that we are checking the maximum length that is being enforce on the text box.

MYSQL Accounts

It is important for any secure website to be cautious on the access given to MYSQL user account on the specific action. For login purposes, the only thing that the user allows to do is to retrieve data from MYSQL table. Hence, other actions such as delete, update, alter etc. should not be given to the login page. If a successful SQL Injection was launched on the site. Imagine the user updating your user account password to the one given. Our security measure will just kick us back to one. Hence, always be cautious on the access given to MYSQL user account.

Utilize IP

Always ensure that IP address is used together with session key after a user has logged into your portal. This can prevent Session attacks and at the same time ensure that the same person is viewing the content of your secure page. You can also use IP to ban certain users from trying to guess your login username or password upon certain tries. However, using IP may mean certain restrictions for certain companies or proxy users from accessing your website. Nonetheless, this can be solved by detecting their connection. You can use this script to detect whether they are behind proxy server

if (
      $_SERVER['HTTP_X_FORWARDED_FOR']
   || $_SERVER['HTTP_X_FORWARDED']
   || $_SERVER['HTTP_FORWARDED_FOR']
   || $_SERVER['HTTP_VIA']
   || in_array($_SERVER['REMOTE_PORT'], array(8080,80,6588,8000,3128,553,554))
   || @fsockopen($_SERVER['REMOTE_ADDR'], 80, $errno, $errstr, 30))
{
    exit('Proxy detected');
}

The above code should allows you to detect even anonymous proxy server.

*****Update 7 Oct 2009

I forgot to mention here that the above script will only be necessary if an IP address cannot be detected (Thanks Julius).

Utilize Cookies

I forgot to mention this important thing to you guys. There is also a need to tie cookie together with session and/or ip to prevent session hijack or cross-site request forgery (CSRF). The hacker might be able to hijack your session through different ways but cookies will still remind on your user client browser.

Cookies can also used for auto logout module by setting the expiry date of the cookie after 15 minutes and if the cookie doesn't exist, the user has been idle for 15 minutes. On the other hand, we can refresh this cookie every user activity. This is one of the many ways to implement auto logout functionality but this is not secure as the cookie can be stolen by hacker and prolong the duration of the cookie expiration time.

Lastly, we talk about locking user upon certain attempts but IP was difficult to be used. This can be solve by utilize cookie to set the number of tries performed by the user/browser. Using cookie is definitely insecure way of keeping track of user attempts but it also creates additional barriers for hackers to overcome. This should be used together with account lock functionality to prevent such weakness in your defense (this means cookie count and account attempts count should not be link together).

Auto Logged Out Mechanism

I forgot this one but one of the readers did not. Implementing an auto logged out mechanism onto your login system can really help prevent CSRF attacks. Since we can't control whether our user leave their account logged in while browsing or surfing the net, we can definitely cover their butt but having this mechanism up to prevent any CSRF or Session attacks. Since both attacks require the user to be logged in.

*****Update End

Lock upon certain fail attempt

This is something that most secure web pages should looked upon. A very good way of locking a user will be as follow,

  1. n times fail attempt locked m minutes
  2. n fail attempt due to 1. locked further m+30 minutes
  3. n fail attempt due to 2. locked for the whole day

An example will be as follows:

  • 3 times fail attempt locked 10 minutes
  • 3 fail attempt due to 3 times fail attempt locked 10 minutes subsequence locked 10+30 minutes
  • 3 fail attempt due to the above will result in whole day lock

You can lock a user based on IP or accounts. It will be better to lock them based on accounts IF proxy IP is unable to detect due to the fact that it is an anonymous proxy. IP should be used otherwise. This will prevent the user from guessing the correct username. On the other hand, if a username was guessed correct the same process can be applied and disabled the account by sending an email to the original author to reactive it. But the same message should be used. (not informative information!) If you are worry of blocking an entire proxy server or company employees, you can just go by account since breaking an account will required certain tries anyway.

SSL Encryption

No matter what you do on the above, without a secure line from the client to your server everything will be meaningless when it comes to packet sniffer which is also known as man in the middle attack. Especially for attacks such as Session Hijack. Password can be send directly into a hacker computer without the need to use brute force. The above mentioned methods definitely can stop newbies but not those that know their stuff. Without such encryption, getting your password won't be that difficult. Here's a video showing how easily it can be done without SSL encryption.

Summary

Any kind of system can still be compromised but the time and effort to compromised such system is another thing to be considered. The above mention methods are ways to make life difficult for hackers so that they will give up on penetrating your system. Hence, any little bit of security measure we can implement on our system is considered as a line of defense. There is never a bad thing by being paranoid in securing your web system. A website is like a man on an open field ready to be shoot at anytime! Do your website a favor. Wear a helmet. (not condom)