Tutorial: How To Sort An Array In JavaScript

In JavaScript, we are given a method Sort() to perform sorting. Although Sort() is said to be used for sorting an array, it can also be used to sort anything other than an array itself. In this article we will discuss all about JavaScript array.

Sort() in JavaScript

By default, the method Sort() in JavaScript takes a given array and sort it in lexicographical order and not alphabetical order! This means that the Sort() method sort a given array in dictionary order. Let's consider the following example of Sort method.

var list =["Zebra", "Monkey", "Donkey"]
list.sort() //["Donkey", "Monkey", "Zebra"]

The above look fine when sorting an array of string but when it comes to number we will face a little problem.

var list =[ 39, 108, 21, 55, 18, 9]
list.sort() //[108, 18, 21, 39, 55, 9]

Looking at the result of the sort function seems to be unsorted but the fact that it is sorted according to lexicographical order does makes it in an ordered form after using the default sort method. Lucky, JavaScript doesn't force you to follow lexicographic order. You may also define a function to sort them in your own way.

Reverse Sort()

We get our result in lexicographical order after we performed a Sort() function. What if we want the reverse order of the sort function instead? In JavaScript, there is a function Reverse() which can help us to reverse the result of the array in the opposite order of the result. Consider the following example to illustrate Reverse() method in JavaScript.

var list =["Zebra", "Monkey", "Donkey"]
list.sort() //["Donkey", "Monkey", "Zebra"]
list.reverse() //["Monkey", "Zebra", "Donkey"]

Simple and powerful.

Customize Sort

The default Sort() function in JavaScript is quite simple and clear. Now, we will look at how we can customize this sort function. JavaScript Sort function does take in a parameter which is a function. Short to say, Sort() Method will sort your array instructed in the given function. However, the return value of the function must be as follow,

  • returns a value less than 0: parameter 'a' value is less than parameter 'b' value. 'a' come BEFORE 'b'.
  • returns a value greater than 0: parameter 'a' value is more than parameter 'b' value. 'a' come AFTER 'b'
  • returns exactly 0: parameter 'a' and 'b' have the same value. no change.

With the above rule, we can create a function that sort our array in numerical order instead of lexicographic order.

function sortmyway(data_A, data_B)
{
	if ( data_A < data_B ) // data_A come before data_B
		return -1;
	if ( data_A > data_B ) // data_A come After data_B
		return 1;
	return 0; // data_A == data_B, no change.

}
var list =[ 39, 108, 21, 55, 18, 9]
list.sort(sortmyway) // [9, 18, 21, 39, 55, 108]

The above example look good but the function seems to be a bit lengthy. You can change the comparison statement in a shorter form using the '?' symbol and we will get a shorter version of the code above.

function sortmyway(data_A, data_B)
{
return ((data_A < data_B) ? -1 : ((data_A > data_B) ? 1 : 0));
}
var list =[ 39, 108, 21, 55, 18, 9]
list.sort(sortmyway) // [9, 18, 21, 39, 55, 108]

We can even shorten the above declaration to perform the same task as shown below,

function sortmyway(data_A, data_B)
{
	return (data_A - data_B);
}
var list =[ 39, 108, 21, 55, 18, 9]
list.sort(sortmyway) //[9, 18, 21, 39, 55, 108]

All the methods above sort the array in ascending order.

Sort Descending order

Using the shortest method i have above, i can declare a sorting function which sort in descending order as follow,

function sortmyway(data_A, data_B)
{
	return (data_B - data_A);
}
var list =[ 39, 108, 21, 55, 18, 9]
list.sort(sortmyway) //[108, 55, 39, 21, 18, 9]

You can also achieve this by using the Reverse() method to eliminate the need to declare two sort function for ascending and descending order.

Random Sort Array

Well, we can also take advantage of the sort function to randomize our array. This way, we do not have to perform any loop which also contribute to function efficiency.

function sortmyway(data_A, data_B)
{
	return 0.5 - Math.random(); //random gives us result between 0 and 1
}
var list =[ 39, 108, 21, 55, 18, 9]
list.sort(sortmyway) //[21, 9, 39, 108, 18, 55]

Summary

Other than array, we can also sort unordered and ordered list. Sort() method in JavaScript can help us perform different kind of sorting in every type of element not restricting to array only. However, using JavaScript to perform sort of other element other than array can be a lot of pain. Personal advice is to use JavaScript framework such as jQuery or Mootools to ease the job. On the other hand, Sort() method can also be used to substitute unnecessary loop to create a more efficient code especially when comparing each element in an array is required. (we just have to eliminate the return value to perform such task) . Even eliminating duplication in an array is possible with Sort() method!

Solutions to Cross-Site Request Forgery Attacks

Let's see..previously i was researching on session attacks and find it really useful in ensuring a web portal to be secured on the server side. Preventing client side security was also discovered on XSS. However, i missed out something important on the client side that is required to protect my users! Another important security measure that i forgotten was cross-site request forgery! Therefore, in this article i will write all the things i know about such attack and how serious it can affect your web portal.

Cross-Site Request Forgery

Cross-site request forgery which is also known as CSRF. CSRF attacks exploit the trust that a site has for a particular user. This means that the attacks is launched by one of the users of the website. Unlike XSS which exploits the trust a user has for a particular site, CSRF exploits the trust that a site has in a user's browser. As mention on XSS article where images can be placed with URL instead of image is the exact thing that is happening on CSRF.

Example of Cross-Site Request Forgery

Let's consider an example of cross-site request forgery. Assume there is a user 'Attacker A' in your system. Your system is an auction site or any site that required credit on an account in order to perform a service or purchase a product. Currently, 'Attack A' do not have any credit. He wants to find a way to get it and CSRF is something he wished to do.
Let's say the attacker send an email to the administrator to enquiry him on a particular issues and embedded some harmful links back to their site as shown below,

Hi,

i have a problem updating the following images 

<img src='http://example.com/givecredit.php?give=clay&credit=9999' width='200px' height='200px'/>
into your form <a href='http://example.com/givecredit.php?give=clay&credit=9999'>this</a> particular page to purchase credit. 
i tried and it return me an error message. Please help me out on this. 

Regards,
Clay

On the PHP part we have a handler givecredit.php as written below,

<?php
	#validate session and cookie to check whether the user is logged in
	if(isLogin())
	{
		$clean['give'] = filter($REQUEST['give']);
		$clean['credit'] = filter($REQUEST['credit']);
		addAmount($clean['give'], $clean['credit']);
		#other instructions
	}
?>

Our not careful administrator entered the link on the email to verify (this is also used to trick administrator of a site to attempt an XSS attack) and an attack was launch on the site easily. Please take note that the display on the email is totally pure text and images without any html code written unless the user change the mode of viewing. On the other hand, the administrator is logged in, the code will be valid and whatever within the code will be run. This is the best way to illustrate cross-site request forgery (CSRF).

Requirement of Cross-site request forgery

An attacker will have to consider a few requirement before CSRF can be achieved.

  • A site that doesn't check the Referrer header (which is common) or a victim with a browser or plugin bug that allows Referrer spoofing
  • A form submission page that is useful for the attacker (example, getcredit.php)
  • Guess all the correct value needed for such submission page to be valid. If there is a need for a valid identifier in the previous page and the attacker can't guess, CSRF will fail.
  • Attack must lure the user to the page or mail to click on the link provided or visit the page to cause the damage

Different CSRF Attacks Location

There are many places that CSRF codes can be placed to lure victim into clicking them. Some doesn't even required any clicking as it is embedded on the page itself. Below are some examples.

#IMG SRC
  <img src="http://example.com/getcredit.php?give=clay&credit=9999">
 
#SCRIPT SRC
  <script src="http://example.com/getcredit.php?give=clay&credit=9999">
 
#IFRAME SRC
  <iframe src="http://example.com/getcredit.php?give=clay&credit=9999">
  
#JavaScript Methods
'Image' Object
  <script>
  var obj = new Image();
  obj.src = "http://example.com/getcredit.php?give=clay&credit=9999";
  </script>
 
#'XMLHTTP' Object, $_POST is vulnerable as shown below
 #IE
<script>
	var post_data = 'give=clay&credit=9999';
	var xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
	xmlhttp.open("POST", 'http://example.com/getcredit.php', true);
	xmlhttp.onreadystatechange = function () { 
	if (xmlhttp.readyState == 4) 
		xmlhttp.responseText;
	
	}; 
	xmlhttp.send(post_data);
</script>
 
#Mozilla
  <script>
  var post_data = 'give=clay&credit=9999';
  var xmlhttp=new XMLHttpRequest();
  xmlhttp.open("POST", 'http://example.com/path/file.ext', true);
  xmlhttp.onreadystatechange = function () {
  if (xmlhttp.readyState == 4)
	xmlhttp.responseText;
  
  };
  xmlhttp.send(post_data);
      </script>

As shown above, using GET, POST or REQUEST can still be vulnerable. But using POST can caused certain level of difficulty for the attackers. Thus, using POST is still preferable.

Solutions to cross-site request forgery

We see above how CSRF can be used to attack our server and caused important monetary value to be wrongly distributed. We won't want this to happen to our users. Hence, some protection has to be implement into our server. On the other hand, end user will also be advisable to perform certain action on a portal to further protect themselves in a website (in the case where CSRF can be launch against you)

End user

Below list some solutions for end user to protect themselves from poor implementation site.

Always log out

It is a good practice to always log out any web application after finish using. Logging out will help ensure any attempt to use your account for attacker benefit is eliminated.

Don't save password/username

It is best not to save any password and username on any browser to prevent other form of attacks. 'Remember Me' feature should not be used as it will usually logged in the user automatically upon accessing the site. Hence, 'Always log out' principle became invalid since every visit will always automatic logged in the user.

Use difference browser for different purpose

Pure surfing and accessing sensitive data on your web application should be separated to prevent attacks on your sensitive data. Default browser will always be used for pure surfing while other non default browser should be used for sensitive data access usage. This will help ensure that links or unknown page accidentally visited will not caused major damage to your sensitive data.

Plain text email

Although it is always secure to view your email in plain text to easily identify any attacks and eliminate script from running through opening an email. However, it is not practical to do this. Thus, always try to use plain text for any suspicious email or check the links on the mail before clicking it.

Avoid Spam Mail

Spam mail are usually mails that contains such attacks which are being reported by other users to the email provider. Hence, avoid displaying external images or not clicking links in "spam" or untrusted e-mails may also help.

Developer

Below listed some ways to protect our users against cross-site request forgery attacks.

Always use POST method

Although using POST can still be vulnerable to CSRF attacks through flash application or XMLHttps request as shown above. Nonetheless, it does make it harder for attackers to exploit your system structure than using pure GET or REQUEST method. However, this doesn't really solved CSRF attack problem.

Always check HTTP Referrer header

Another simple counter measurement against CSRF attacks is to check the HTTP Referrer header. However, the header is optional and may not be present. In some browsers, it is disabled and is not available when interactions occur between HTTPS and HTTP served pages. The risk of header spoofing exists, and tracking the valid sources of invocations may be difficult in some applications. Hence, empty or invalid HTTP Referrer header should be marked as dangerous and access should be denial.

Automatic Log out

Implement automatic log out mechanism for your web application will greatly help your user to secure their account from being attacked. One of the criteria that makes CSRF attack possible is when user remain logged in to the website while links or page is being visited. Automatic log out mechanism can help minimize such mistake made by the users and reduce the risk of CSRF attacks.

Authenticate POST and Cookie data

Another security measure is to authenticate your variable POST and Cookie data. We can ensure that the global variable is being authenticate by ensuring certain criteria is being met such as length, data type, value and etc. This can help ensure other form of attack is eliminated and possible CSRF attack is being minimized. On the other hand, Cookie data can be manipulated by attacker and is required to be authenticate always through some information such as information previously stored in the cookie that can be verify through your database or user browser.

Double Confirm Form Submission

Another simple method you can apply is to write a simple script to alert the user of an action to be performed on behalf of the user before processing so that the user is aware that some form of submission is being create out. Another more proper way of handling such confirmation is to send in an email or sms to authenticate the action by providing an action code to be submitted by the account user themselves. This will help prevent the attackers from getting what they want when they do not hold the email or sms of the system provided. (sniffing is possible but the whole process harden the system security)

Secret Key Required

Make all form submission required a secret key to be passed along. The key will act as a protection for our user as the key is generated by a self made authentication process that will change in every form submission. typically this key is tied to the user session and validate that you get the same value back in the form post. In this way, we can ensure that the session contains such secret key and post method also return such key to verify that the submission is valid and previous page was a form. The form is the one which initial the session key and post key that will be bought to the submission page. If the user have not visited the form page and was bought directly to the form submission page, the attack will fail since the key wasn't provided and generated on the form page previously. Consider the following form which create the key initially.

<?php
session_start();
$key = md5(uniqid(rand(), TRUE));
$_SESSION['key'] = $key;
$_SESSION['key_time'] = time();
 
?>
<form action="givecredit.php" method="post">
<input type="hidden" name="key" value="<?php echo $key; ?>" />
<p>
To: <input type="text" name="give" /><br />
Credit: <input type="text" name="credit" /><br />
<input type="submit" value="Submit" />
</p>
</form>

On the form submission page we will validate whether the submission and post value is the same.

<?php
if(isset($_POST['key']) && isset($_SESSION['key']))
if ($_POST['key'] == $_SESSION['key'])
{
   $key_age = time() - $_SESSION['key_time'];
	if ($key_age <= 600)
	{
		/* Less than ten minutes has passed. */
	}
}
?>

if we didn't get the post key value and session key value to be identical, we can assume there is an attempt of attack on our system and you might consider to log that up for further investigation and protection.

Below contains some recommended reading which is pretty good in this topic.

Good Reading

Below are some resources on CSRF

Summary

Even Digg, GMail, and Wikipedia suffer CSRF attacks previously. Do not make such mistake and protect your system carefully before it become a problem in your system. The solutions above might not be full bullet proof solution for future cross-site request forgery attacks. Nonetheless, it can be used for discussion on solutions of future such attack.

Solutions To Session Attacks

Recently i wrote two other security article on XSS and SQL Injection. I find many interesting facts and solutions on those topic that i research about and wanted to know more about other security measure. Thus, in this article i will discuss on different type of session attacks and how we can better protect ourselves against these attacks to better secure our web portal.

Session attack is nothing more than session hijacking. The most important information in session attack is to obtain a valid valid session identifier (SID). There are three common methods used to obtain a valid session identifier.

  • Session Prediction
  • Session Capture
  • Session Fixation

Session Prediction

Prediction refers to guessing a valid session identifier. With PHP's native session mechanism, the session identifier is extremely random. Hence, it is difficult to guess such SID. Although it is not the weakest point of a secure website. There are still chances of accessing the site through this method.

Solution To Session Prediction

Use of a longer random number or string as the session key. This reduces the risk that an attacker could simply guess a valid session key through trial and error or brute force attacks.

Session Capture

Capturing a valid session identifier is the most common type of session attack. Rather than predicting a correct session identifier is much easier. This approach is also known as Session Sidejacking, where the attacker uses packet sniffing to read network traffic between two parties to steal the session cookie. Unsecured Wi-Fi hotspots are particularly vulnerable, as anyone sharing the network will generally be able to read most of the web traffic between other nodes and the access point.

Solution To Session Capture

Encryption of the data passed between the parties; in particular the session key. This technique is widely relied-upon by web-based banks and other e-commerce services, because it completely prevents sniffing-style attacks. However, it could still be possible to perform some other kind of session hijack. Many web application apply SSL only on login page where session id can still be sniff out on subsequence pages. The password of such application is protected but not the session.

Session Fixation

Session fixation attacks attempt to exploit the vulnerability of a system which allows one person to fixate another person's session identifier (SID). Most session fixation rely on session identifiers being accepted from URLs (query string) or POST data.

Scenario Of Session Fixation Attacks

Here are some ways session fixation can be launched.

Simple Attack

The most simple way of an attack that can be launched due to website vulnerability.

  1. Attacker A knows http://unsafe.com is an unsafe site that accept SID directly through query string and no validation is being done on the site.
  2. Attack A send an email to Victim B 'Someone tried to access your bank account. Please access your account at http://unsafe.com?SID=H2SK9XSU1fL197DQ621Sh to change your password.' Attacker A is trying to fixate the SID to H2SK9XSU1fL197DQ621Sh.
  3. Victim B clicked on the URL provided and was bought to the login site.
  4. Victim B logged in with his access and tried to verify.
  5. Attack A then used the same URL to gain Victim B access since the session has been fixed to H2SK9XSU1fL197DQ621Sh.

Server Generated SID Attack

Misconcept of server generated session identifier is safe from fixate. Unfortunately not.

  1. Attacker A visits http://unsafe.com/ and checks which SID is returned. For example, the server may respond: Set-Cookie: SID=9AS82120DK8E0DI.
  2. Attacker A send in an email to Victim B. 'Please join our latest promotion at 'http://unsafe.com?SID=9AS82120DK8E0DI'.
  3. Victim B logged in and caused the fixate on 9AS82120DK8E0DI. Finally, Attacker A enters the same URL to gain unauthorizes access.
  4. Typically the same way as simple attack. The only differences is that the session identifier is being created by the server instead of the unsecured one.

Cross-Site Cooking Attack

Cross-site cooking is a type of browser exploit which allows a site attacker to set a cookie for a browser into the cookie domain of another site server. It exploits browser vulnerabilities although the original site was secure.

  1. Attacker A sends Victim B an e-mail: "Hey, celina has recommend you a new site at http://unsafe.com/"
  2. Victim B visits http://unsafe.com/, which sets the cookie SID with the value H2SK9XSU1fL197DQ621Sh into the domain of http://safe.com/
  3. Victim B then receives an e-mail from Attacker A, "Due to new implementation we will required you to login to http://safe.com/ to verify your bank account".
  4. Once Victim B logs on, Attacker A can use her account using the fixated session identifier.

Cross-Subdomain Cooking Attack

This is the same thing as cross site cooking, except that it does not rely on browser vulnerabilities. Rather, it relies on the fact that wildcard cookies can be set by one subdomain that affect other subdomains.

  1. A web site such as www.blogprovider.com hands out subdomains to untrusted third parties
  2. Attacker A who controls evil. blogprovider.com, lures Victim B to his site
  3. A visit to evil.blogprovider.com sets a session cookie with the domain .blogprovider.com on Victim's B browser
  4. When Victim B visits www.blogprovider.com, this cookie will be sent with the request, as the specs for cookies states, and Victim B will have the session specified by Attacker A cookie.
  5. If Victim B now logs on, Attacker A can use her account.

Victim B can be a administrator on blogprovider.com/administrator.

Each session attack scenario has resulted in Privilege escalation or Cross-calation which exploit a bug or flaw in the system to gain unauthorizes access. Such attacks are dangerous as Attack A can spy on Victim B on whatever he is doing on the system. If Victim B decides to purchase something on this site and enters her credit card details, Attack A may be able to harvest Victim B history access to see such sensitive data and details.

Session Fixation Attack

In order to better illustrate session fixate, we will consider the following example,

<?php
session_start();
if (!isset($_SESSION['visits']))
{
	$_SESSION['visits'] = 1;
}
else
{
	$_SESSION['visits']++;
}
echo $_SESSION['visits'];
?>

The above state that every different browser or new cookie session should have a start index of '1'. To demonstrate session fixation, first make sure that you do not have an existing session identifier, then visit this page with domain.com?PHPSESSID=1234. Next, with a completely different browser (or even a completely different computer), visit the same URL again with domain.com?PHPSESSID=1234. You will notice that the output show 2 instead of 1 because the session was continue! This is session fixate where the same session is used to continue previous session although you were not the first initializer.

Solutions To Session Fixation Attacks

Although Session Fixation is widely used. There are also many solutions for such attacks.

Do not accept session identifiers from GET / POST variables

We know from XSS attack article that global variable is dangerous. Session Fixation is one of the live example of such danger. We are all aware from this article that session fixation is achieve through query string or POST variable. Thus, prevent using such method for SID one of the best solution you can undertake to prevent simplify attack.

Additionally, such usage also increase the risk of:

  1. SID is leaked to others servers through the Referrer
  2. SID is leaked to other people through communication channels and social network
  3. SID is being stored in many places (browser history log, web server log, proxy logs, ...)

Change Important Session identifier

Session Fixation can be largely avoided by changing the session ID when users log in. In every important event, changing the session identifier will prevent attackers from accessing these important event. When the victim visits the link with the fixed session id, however, they will need to log into their account in order to do anything "important" as themselves. At this point, their session id will change and the attacker will not be able to do anything "important".

Store session identifiers in HTTP cookies

The session identifier on most modern systems is stored by default in an HTTP cookie, which has a moderate level of security. However, modern systems often accept session identifiers from GET/POST as well. The web server configuration must be modified to protect against this vulnerability.

; Whether to use cookies.
session.use_cookies = 1

; This option enables administrators to make their users invulnerable to
; attacks which involve passing session ids in URLs; defaults to 0.
session.use_only_cookies = 1

Utilize SSL / TLS Session identifier

When enabling HTTPS security, some systems allow applications to obtain the SSL / TLS session identifier. Use of the SSL/TLS session identifier is very secure, but many web development languages do not provide robust built-in functionality for this.
SSL/TLS session identifiers may be suitable only for critical applications, such as those on large financial sites, due to the size of the systems. This issue, however, is rarely debated even in security forums.

Regenerate SID on each request

Similar to 'Change Important Session identifier', however, this will regenerate the session identifier every single time a page is being request. This will further enhance the security since every single request by the user will eventually change the session identifier. Even if someone were able to capture session identifier through sniffing, the session id will eventually change which will make attacks difficult.

Accept only server generated SIDs

One way to improve security is not to accept session identifiers that were not generated by the server. Making life difficult for attacker is also one of the most important way of improve security.

#remove any session that may exist
if (!isset($_SESSION['SERVER_GENERATED_SID'])) {
   session_destroy(); 
}
#generate a new session id through built-in function
session_regenerate_id(); 
$_SESSION['SERVER_GENERATED_SID'] = true;

Logout function

Session Fixation will only be active when the known session identifier is the same. Thus, the attacker known session identifier will be invalid when the user logout themselves. Hence, having the following function is critical to improve session security.

if (isset($_POST['LOGOUT']))
   session_destroy(); // destroy all data in session

Time-out Session Identifier

Another very critical process of securing a web application is to implement a time out function to destroy the session whenever a session has expired. A session will expired after a given time. This defense is simple to implement and has the advantage of providing a measure of protection against unauthorized users accessing an authorized user's account by using a machine that may have been left unattended.

Store a session variable containing a time stamp of the last access made by that SID. When that SID is used again, compare the current timestamp with the one stored in the session. If the difference is greater than a predefined number, say 5 minutes, destroy the session. Otherwise, update the session variable with the current timestamp.

Destroy session if Referrer is suspicious

As mention on the scenario of session fixation, cross site cooking required an access to a bad URL and set the cookie session to the real URL. Destorying the session will prevent such attack from happening.

#check whether the referer is from our domain.
if (strpos($_SERVER['HTTP_REFERER'], 'http://mywebsite.com/') !== 0) {
   session_destroy(); // destroy all data in session
}
session_regenerate_id(); // generate a new session identifier

Verify IP

One way to further improve security is to ensure that the user appears to be the same end user (client). This makes it a bit harder to perform session fixation and other attacks. As more and more networks begin to conform to RFC 3704 and other anti-spoofing practices, the IP address becomes more reliable as a "same source" identifier. Therefore, the security of a web site can be improved by verifying that the source IP is consistent throughout a session.

if($_SERVER['REMOTE_ADDR'] != $_SESSION['PREV_REMOTEADDR']) {
   session_destroy(); // destroy all data in session
}
session_regenerate_id(); // generate a new session identifier
$_SESSION['PREV_REMOTEADDR'] = $_SERVER['REMOTE_ADDR'];

However, there are some points to consider before employing this approach.

  • Several users may share one IP. It is not uncommon for an entire building to share one IP using NAT.
  • Inconsistent IP as the users are behind proxies (such as AOL customers) or from mobile/roaming.

User Agent

Although the attacker may be able to change the user agent to match the one on the session. However, it makes the process even more difficult and may help prevent some attacker from penetrating through the session. A web application might make use of User-Agent detection in attempt to prevent malicious users from stealing sessions.

#check whether the stored agent is similar to user agent
if ($_SERVER['HTTP_USER_AGENT'] !== $_SESSION['PREV_USERAGENT']) {
   session_destroy(); // destroy all data in session
}
session_regenerate_id(); // generate a new session identifier
$_SESSION['PREV_USERAGENT'] = $_SERVER['HTTP_USER_AGENT'];

Full Defense

Creating multiple layer of defense mention above into a fully functional method to be used in every session authentication.

function validate_session($url)
{
	if (strpos($_SERVER['HTTP_REFERER'], $url) !== 0 ||
		isset($_GET['LOGOUT']) ||
		$_SERVER['REMOTE_ADDR'] !== $_SESSION['PREV_REMOTEADDR'] ||
		$_SERVER['HTTP_USER_AGENT'] !== $_SESSION['PREV_USERAGENT'])
	  session_destroy();
    #time-out logic

	session_regenerate_id(); // generate a new session identifier

	$_SESSION['PREV_USERAGENT'] = $_SERVER['HTTP_USER_AGENT'];
	$_SESSION['PREV_REMOTEADDR'] = $_SERVER['REMOTE_ADDR'];
}

Other Attacks

Cross-site scripting, where the attacker tricks the user's computer into running code or link which is treated as trustworthy because it appears to belong to the server, allowing the attacker to obtain a copy of the cookie or perform other operations.

Alternatively, an attacker with physical access can simply attempt to steal the session key by, for example, obtaining the file or memory contents of the appropriate part of either the user's computer or the server.

Summary

Session attacks are common among the attack used on secure website. Effort has to be made to improve session security to prevent any thief from happening. The solutions above might not be full bullet proof solution for future session attacks. Nonetheless, it can be used for discussion on solutions of future such attack.

Tutorial: jQuery Select Box Manipulation Without Plugin

In jQuery, working with select box required some additional knowledge and interaction with jQuery. You may have some problem manipulating select box during your web development on jQuery. In this article we will discuss how you can solve this without any additional plugin to kill efficiency.

Create Selext Box In jQuery

Create a select box is very simple and straight forward. Just write a string with the normal select tag and a select box is created in jQuery

jQuery('#some_element').append('<select></select>');

I bet everyone would have tried this and it work. However, manipulating might be a more challenging task.

Add Option In Select Box With jQuery

One easy way is to create a string with the whole element and create it straight away

//obj is the list of option values
function(obj)
{
	var create = '<select id="test">';
	for(var i = 0; i < obj.length;i++)
	{
		create += '<option value="'+obj[i]+'">'+obj[i]+'</option>';
	}
	create += '</select>';
	jQuery('#some_element').append(create);
}

Another way to create a list of elements is to create its option and append it in using pure jQuery.

function(id, obj)
{
	jQuery('#some_element').append('<select id="'+id+'"></select>');
	jQuery.each(obj, function(val, text) {
		jQuery('#'+id).append(
		jQuery('<option></option').val(val).html(text)
	);})
}

You may not be familiar what i wrote above. Hence, a more javascript approach is shown below.

function(id, obj)
{
	jQuery('#some_element').append('<select id="'+id+'"></select>');
	for(var i = 0; i < obj.length;i++)
	{
		jQuery('#'+id).append('<option value="'+obj[i]+'">'+obj[i]+'</option')
	}
}

Get Select Box Value/Text In jQuery

Sometimes we want to know what is the value of the selected option. This is how we do it. Please bear in mind that there shouldn't be any spaces between the : and selected.

//#selectbox is the id of the select box
jQuery('#selectbox option:selected').val();

On the other hand, we can get the text of the option by doing this.

//#selectbox is the id of the select box
jQuery('#selectbox option:selected').text();

What if you know the value of the options you want to get instead of the one selected?

//#selectbox is the id of the select box
$("#selectList option[value='thisistheone']").text();

How about the first element on the select box?

//#selectbox is the id of the select box
$("#selectList option:first").text()

How about the n element on the select box?

//#selectbox is the id of the select box
$("#selectList option:eq(3)").text()

How about getting all elements but the first and last one in a select box?

//#selectbox is the id of the select box
$("#selectList option:not(option:first, option:last)").each(function(){
$(this).text();
});

Get Multiple Selected Value/Text In jQuery Select Box

Now we want to try to retrieve multiple selected values, we can do it easily with the following code.

	jQuery('#some_element:selected').each(function(){
		alert(jQuery(this).text());
		alert(jQuery(this).val());
	});

How about storing these values?

	var current = [];
	jQuery('#some_element:selected').each(function(index, selectedObj){
		current[index] = $(selectedObj).text();
	});

This way we eliminate the additional index needed to follow through the loop! How about shorten the cold a bit?

var foo = jQuery('#multiple :selected').map(function(){return jQuery(this).val();}).get();

This way we eliminate the need to create an array.

Remove Element In Select Box With jQuery

So we can get and add element into the select box. How about remove them? Basically, you will need to use one of the get element method describe above before applying the remove instruction.

jQuery('#selectbox: selected').remove();

Here we will remove all elements except the first and last one.

//#selectbox is the id of the select box
$("#selectbox option:not(option:first, option:last)").remove();

Select an option in the select box with jQuery

If you want to select an option in the select box, you can do this.

jQuery('#selectbox option[value="something"]').attr('selected', 'selected');

all option will be selected in this case.

UnSelect an option in the select box with jQuery

If you want to unselect an option in the select box, you can do this.

jQuery('#selectbox option[value="something"]').attr('selected', false);

all option will be unselected n this case.

OnChange find selected option from the select box

onchange find select box selected item.

$('#selectbox').change(function(){
	var val = $(this).find('option:selected').text();
	alert('i selected: ' + val);
});

onchange find select box selected items.

$('#selectbox').change(function(){
	$(this).find('option:selected').each(function () {
		alert('i selected: ' + $(this).text());
	}
});

Summary

There are definitely other tricks to manipulate select box. The above are just some of it.

Solutions to Cross-Site Scripting (XSS) Attack

Recently i wrote an article on Solutions to SQL Injection Attack that have all the great solutions to tackle SQL Injection Attack. In this article, i would like to discuss with you about Cross-Site Scription attack which is also known as XSS attack.

Cross-Site Scripting Attack

What is cross-site scripting attack? You can easily get a definition written on Wikipedia. It is a type of computer security vulnerability typically found in web applications which allow code injection by malicious web users into the web pages viewed by other users. Often look perfectly fine on the end-users side who may be subject to unauthorized access, theft of sensitive data, and financial loss. Here are a few cross-site scripting attack scenarios you may find interesting.

Simple persistent attack

  1. Mallory posts a message to a social network.
  2. When Bob reads the message, Mallory's XSS steals Bob's cookie.
  3. Mallory can hijack Bob's session and impersonate Bob.

DOM-based attack

  1. Mallory sends the URL of a maliciously constructed web page to Alice, using email or another mechanism.
  2. Alice clicks on the link.
  3. The malicious web page's JavaScript opens a vulnerable HTML page installed locally on Alice's computer.
  4. The vulnerable HTML page contains JavaScript which executes in Alice's computer's local zone.
  5. Mallory's malicious script now may run commands with the privileges Alice holds on her own computer.

Non-Persistent

  1. Alice often visits a particular website, which is hosted by Bob. Bob's website allows Alice to log in with a username/password pair and store sensitive information, such as billing information.
  2. Mallory observes that Bob's website contains a reflected XSS vulnerability.
  3. Mallory crafts a URL to exploit the vulnerability, and sends Alice an email, enticing her to click on a link for the URL.
  4. Alice visits the URL provided by Mallory while logged into Bob's website.
  5. The malicious script embedded in the URL executes in Alice's browser, as if it came directly from Bob's server. The script can be used to send Alice's session cookie to Mallory. Mallory can then use the session cookie to steal sensitive information available to Alice (authentication credentials, billing info, etc) without Alice's knowledge.

Persistent

  1. Bob hosts a web site which allows users to post messages and other content to the site for later viewing by other members.
  2. Mallory notices that Bob's website is vulnerable to a type 2 XSS attack.
  3. Mallory posts a message to Bob's website.
  4. Later, Alice views Mallory's message.
  5. Alice's session cookies or other credentials can be taken and sent to Mallory, without her knowledge.
  6. Mallory logs into Bob's website as Alice, and can see sensitive information (billing info etc.), or post messages on her behalf.

Identity Attack

  1. Bob hosts a site that allows users to post messages which includes a stored list of user names as recommendations.
  2. Alice is a regular visitor to the recommendation-based site; she uses an alias to protect her identity.
  3. Mallory knows one or more of Alice's email addresses but not her identity alias.
  4. Mallory uses social engineering to send a disguised recommendation link or the link to a carefully constructed redirect page which recommends a staged posting to Bob's site.
  5. Alice clicks on the link. Her session cookies or willing-login trigger the recommendation.
  6. Mallory reads the recommendation list and discovers Alice's online identity.

The above scenarios are taken from Wikipedia itself which i find it most appropriate to demonstrate the danger of XSS attack.

Solutions

It is well said that the responsibility of preventing XSS attack should not only be held by the developers. End user will really required to know this to better protect themselves from such attacks. It is always better to believe in yourself than others when it comes to security. In this article, we will discuss solutions to better secure ourselves and our web application. Although there are many risk with XSS attack, defending against it is much easier than you might though.

Developers

Filter all foreign data

Anything that will store in our database for future display to other user entered by users are consisted as foreign data. Ensure that all these data are being filter correctly will greatly prevent XSS attack from occurring on your website. Although it may sound easy but it does take discipline to always filter these data whenever there is such input. Especially on larger system where many developers are working on it. Simple filter such as htmlentities() can help eliminate many Cross-site scripting concern.

$filter_input = htmlentities($post['userinput'])
#use $filter_input

Use existing functions

Always use existing functions exist on PHP. Functions like htmlentities(), strip_tags(), and utf8_decode() can be useful. Try not to create your own function for filtering purposes as the functions in build in PHP are usually much faster and more secure to be used. Here are some functions that within PHP that are great for valid or filter user input

  • htmlentities()
  • strip_tags ()
  • utf8_decode ()
  • htmlspecialchars()
  • ctype_digit()
  • ctype_alnum()

Use a whitelist approach

Always assume data to be invalid until it is proved valid. This means that checking the length of the given input, validate the correct type, using regular expression to further validate the creditability till the extreme case you can imagine. This will help prevent any circumstances when the filter failed and caused the script to access your website.

Use a strict naming convention

We all know big systems are usually build by a few developers. Hence, it is important to use a strict naming convention so that whenever a developer look at the code he is able to identify what the other developer is trying to accomplished (you never know what some developer will do during refactoring to make the code more efficient. Yes, they remove these important stuff) and whether the data has been tainted.A lack of clarity yields confusion, and this breeds vulnerabilities. It is a good practice for developer to always be suspicious towards these global variables ($_POST, $_GET, $_REQUEST, etc.). An example of such strict naming convention can be illustrate below,

<?php
$clean = array();
#check whether it is a float, this is just a demo and more validation should be applied before it is clean.
if ($_POST['num'] == strval(floatval($_POST['num'])))
{
$clean['num'] = $_POST['num'];
}
#we use clean array onwards.
?>

Initialize your data

It is a good practice to always initialize your data although it is not necessary to do that in PHP. Since any variable that has not been initialize should always be considered as tainted. It is important to untainted it by initialize them. The user does not have another opportunity to send data as the entire HTTP request has been received, hence no data can be injected into your script (even if register_globals is enabled). Assume register_globals is enabled an attacker can easily make our clean variable into a malicious code if we did not initialize it. Consider the following code,

domain.com?clean=malicious_code

because we did not initialize clean array, clean now contains malicious code that may caused damage to our system.

#this part was invalid
if ($_POST['num'] == strval(floatval($_POST['num'])))
{
$clean['num'] = $_POST['num'];
}
#we use clean array onwards.
?>

Cookie Security

Another form of cross-site scripting attack is through cookie security. Many website uses cookie for various reason such as store information, retrieve information, track activities and etc,. However, most web applications rely on session cookies for authentication between individual HTTP requests (the remember me box on login page). We all are aware that client script have access to such cookie and simple XSS script can be made to retrieve such authentication to fake user access. To mitigate this particular threat, we can tie session cookies to the IP address of the user who originally logged in, and only permit that IP to use that cookie. but it will obviously break when an attacker is behind the same NATed IP address or web proxy.

Use BBCode

Many website such as forums, blogs, CMS or other communication system provides the ability to enhance that content by posting formatted text. However, these formatted text is vulnerable against Cross-site scripting attack. Many will uses BBCode on their system to provide user with formatted text and at the same time protect themselves against such attack. Consider the following example of BBCode

[b]bold[/b] text 
to
<b>bold</b> text

[color=blue]blue text[/color]
to
<span style="color: blue">blue text</span>

You can know more about BBCode in Wikipediawhere more example and explanation is being provided on BBCode. However, using such tag doesn't guarantee XSS security. Consider the following attack example within BBCode,

[url=http://hungred.com]Web development bookmark[/url]
to
<a href="http://hungred.com">Web development bookmark</a>.

The above illustrate a normal anchor tag BBCode. However, if i placed a JavaScript into the BBCode, it is still valid in BBCode,

[url=javascript:alert('Got you!')]Web development bookmark[/url]
to
<a href="javascript:alert('Got you!')">Web development bookmark</a>.

That is why whitelist approach is needed to always prevent such attack from coming. Similarly, in some lower versions of Internet Explorer (IE6 and below), URL format is allowed and will execute Javascript which we will have to take care as well.

XSS CheatSheet

For developers who are concern about XSS attack. (which you should) Please visit this XSS (Cross Site Scripting) Cheat Sheet to further test and protect against XSS attack.

End User

Disabled JavaScript

Many end-users (includes developers) who are well aware of XSS attack and the harm that it may bring upon the user will have their JavaScript disabled on their browsers. Since Cross-Site scripting is using JavaScript to harm users. Disabled such feature is the best way to prevent any attack from Cross-Site scripting. Although this will means that many newer site which only deploy JavaScript may not be accessible, this will also means that many developer will have to ensure that their site is fully protected against such attack. Users can disabled JavaScript and only allows those that are trusted. This approach act as a white list approach where only trusted website has JavaScript enabled to prevent any damage from occurring.

Disabled Cookie

User may want to disabled cookie in order to protect themselves against XSS attack or older browser may not even support cookies. Developers will have to think of alternative ways to provides functionality that required cookies than depending on it.

Summary

Developer must ensure the safety of its visitors and build a safer system for end users. On the other hand, end-user (including developers) will need to know the type of attacks used by attackers to prevent such attacks. The solutions above might not be full bullet proof solution for future Cross site scripting attack. Nonetheless, it can be used for discussion on solutions of future such attack.