Saturday, 23 November 2013

How to secure jQuery AJAX calls in PHP from hackers?

How to secure jQuery AJAX calls in PHP from hackers?

If you are making jQuery AJAX calls in your PHP website, please ensure that those jQuery AJAX calls are secure from website hackers. Your code should not be vulnerable to hackers. Below are some methods and steps which need to be taken to secure your jQuery AJAX calls to PHP files. I am writing this post because I had written a simple post "How to call PHP function from JavaScript function? Always use AJAX." without mentioning any security code. I got following comment on that post:

"Your code is very vulnerable. You're not filtering the $_POST variable at all. This opens yourself to HTML injection. A hacker could pwn your web site very quickly if you used this code. Careless examples like yours is exactly why so many web sites are hacked."

That's why this is my small attempt to make your jQuery AJAX calls secure. 

1. Use $_SERVER['HTTP_X_REQUESTED_WITH']

This is a basic check to see if the request is an Ajax request or not?

if(!empty($_SERVER['HTTP_X_REQUESTED_WITH']) &&       strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') 
{
    //Request identified as ajax request
}

However you should never base your security on this check. It will eliminate direct accesses to the page if that is what you need.

2. Use $_SERVER['HTTP_REFERER']

if(@isset($_SERVER['HTTP_REFERER']) && $_SERVER['HTTP_REFERER']=="http://yourdomain/ajaxurl")
{
 //Request identified as ajax request
}

But not all browsers set it. So don't properly rely on it but yes, to some extent it can secure your webpage.

Nobody can AJAX your site from other domain, but always can connect and drieclty send http request, for example by cURL.

JavaScript running on another domain cannot access any page on your domain because this is a violation of the Same-Origin Policy. The attacker would need to exploit an XSS vulnerability in order to pull this off. In short you don't need to worry about this specific attack, just the same old attacks that affect every web application.

3. Generate Access Tokens

$token = md5(rand(1000,9999)); //you can use any encryption
$_SESSION['token'] = $token; //store it as session variable

You can create some token in cookies, that will be also seen from jquery request, but that solution can also be hacked.

4. Always check $_POST variables in your PHP file whether those are set or not? Whether there is valid value in $_POST or not before executing the actual PHP code.

Basic code snippet for securing your jQuery AJAX calls in PHP

Step-1 : Generate Token System For All Web-Service:

Generating Token :

<?php
  session_start();
  $token = md5(rand(1000,9999)); //you can use any encryption
  $_SESSION['token'] = $token; //store it as session variable
?>

Step-2 : Use it while sending ajax call:

var form_data = 
{
  data: $("#data").val(), //your data being sent with ajax
  token:'<?php echo $token; ?>', //used token here.
  is_ajax: 1
};

$.ajax({
  type: "POST",
  url: 'yourajax_url_here',
  data: form_data,
  success: function(response)
  {
    //do further
  }
});

Step-3 : NOW, Let's secure ajax handler PHP file with,

session_start(); 
if($_SERVER['HTTP_X_REQUESTED_WITH'] == 'XMLHttpRequest') 
{
  //Request identified as ajax request

  if(@isset($_SERVER['HTTP_REFERER']) &&    $_SERVER['HTTP_REFERER']=="http://yourdomain/ajaxurl")
  {
   //HTTP_REFERER verification
    if($_POST['token'] == $_SESSION['token']) {
      //do your ajax task
      //don't forget to use sql injection prevention here.
    }
    else
   {
      header('Location: http://yourdomain.com');
    }
  }
  else 
  {
    header('Location: http://yourdomain.com');
  }
}
else 
{
  header('Location: http://yourdomain.com');
}

4 comments:

  1. you can avoid nesting the if statements for a little bit more readable code.

    i like something like this.


    <?php
    session_start();
    $bBadRequest = false;
    if($_SERVER['HTTP_X_REQUESTED_WITH'] != 'XMLHttpRequest')
    $bBadRequest = true;

    if(!isset($_SERVER['HTTP_REFERER']) || $_SERVER['HTTP_REFERER'] != "http://yourdomain/ajaxurl")
    $bBadRequest = true;

    if($_POST['token'] != $_SESSION['token'])
    $bBadRequest = true;

    if($bBadRequest) {
    header('Location: http://yourdomain.com');
    die;
    }

    // valid request, now we can do our ajax stuff

    ReplyDelete
  2. Yes, your way is more readable. Thanks for your suggestion.

    ReplyDelete
  3. None of this is fool proof, so I think it is pointless.

    ReplyDelete
  4. http://www.burbagssale2013.com/ Burberry Outlet
    http://www.airmaxshoesfactory.com/ Air Max Shoes
    http://www.coachblackfriday2014.com/ Coach Black Friday
    http://www.coach-storeoutletonline.com/ Coach Black Friday
    http://www.coachcoachoutlet.com/ Coach Cyber Monday
    http://www.coachxfactory.com/ Coach Factory
    http://www.coach-factoryoutletonline.net/ Coach Outlet Factory
    http://www.coach-outletonlineusa.com/ Coach Outlet USA
    http://www.coach-pursesfactory.com/ Coach Purses Factory
    http://www.coachpurseusa.com/ Coach Purses USA
    http://www.coach-storeoutlet.com/ Coach Store Outlet
    http://www.coach-pursesonline.com/ Coach Purses On Sale
    http://www.monsterbeatsbydres.com/ Monster Beats Outlet
    http://www.louis-vuittonblackfriday.com/ Louis Vuitton Outlet
    http://www.lv-guccishoesfactory.com/ Louis Vuitton Factory
    http://www.marcjacobsonsale.com/ Marc Jacobs On Sale
    http://www.mcmworldwides.com/ MCM Outlet
    http://www.mcmoutlet-jp.com/ MCM 店铺
    http://www.oakleysunglassesfactory.com/ cheap oakley sunglasses
    http://www.michaelkorsmas.com/ Michael Kors Outlet
    http://www.michaelkors.so/ Michael Kors Outlet
    http://www.michaelkorsfactory-store.com/ Michael Kors Factory
    http://www.michaelkorsoutletr.com/ Michael Kors Outlet
    http://www.michael-korsfactoryonline.com/ Michael Kors Factory Online
    http://www.newcoachfactoryoutlet.com/ Coach Factory Outlet
    http://www.north-faceoutletonlines.net/ North Face Outlet Online
    http://www.polo-outletstore.com/ Polo Outlet Store
    http://www.ralph-laurenhome.com/ Ralph Lauren UK
    http://www.saclongchamppairs.com/ Sac Longchamp Pairs
    http://www.tcoachoutletonline.com/ Coach Outlet Online
    http://www.the-coachfactoryoutlet.com/ Coach Factory Oultet
    http://www.barbour-jacketsoutlet.com/ Barbour Jackets Outlet Online
    http://www.canada-gooser.com/ Canada Goose Outlet
    http://www.guccishoesuk-2014.com/ Gucci Outlet Online
    http://www.michaelkorsstates.com/ Michael Kors Outlet
    http://www.moncler-clearance.com/ Moncler Clearance
    http://www.famousbagsmall.com/
    http://www.moncler-jacketsoutletonline.com/ Moncler Jackets Outlet Online
    http://www.northsclearance.com/ North Clearace Outlet
    http://www.polo-ralphlaurenonline.com/ Polo Ralph Lauren Outlet Online
    http://www.woolrich-clearance.com/ Woolrich Clearance
    http://www.cvshopfactory.com/ shop.coachfactory.com
    http://www.mksfactoryoutlet.com/ Michael Kors Factory Outlet
    http://www.zxcoachoutlet.com/ Coach Outlet Online USA
    http://www.thebeatsbydre.net/ Beats by Dre
    http://www.vipbagsmall.com/
    http://www.newoutletonlinemall.com/ Coach Purses Outlet Online
    http://www.clickmichaelkors.com/ Michael Kors USA

    ReplyDelete