• 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Protecting ajax-controllers globally

#1
[eluser]Unknown[/eluser]
Under AJAX-controller I mean a function of controller that handles only AJAX-requests.
Is there any methods against protecting ajax-controllers from spam of non my domain requests, DoS, etc? I mean we can check HTTP_X_REQUESTED_WITH, HTTP_REFERER, session cookie (since AJAX-calls can be maid only from pages of my site and each page sets session cookie) and soon HTTP_ORIGIN.

In my config I use best practices:
Code:
$config['sess_encrypt_cookie'] = TRUE;
$config['sess_use_database'] = TRUE;

Could I write something like this?

Code:
<?php  if ( ! defined('BASEPATH')) exit('error');
/**
* Session Class
*/
class MY_Session extends CI_Session
{
/**
  * Session Constructor
  *
  * The constructor runs the session routines automatically
  * whenever the class is instantiated.
  */
public function __construct($params = array())
{
  if(isset($_SERVER['HTTP_X_REQUESTED_WITH']) && $_SERVER['HTTP_X_REQUESTED_WITH'] == 'XMLHttpRequest') // this is ajax-request
  {
   // lets protect AJAX-controllers globally

   // session cookie must be set since AJAX-calls can be made only from pages of my site
   if(!isset($_COOKIE[$this->config->item('sess_cookie_name')]))
    exit;
   // anonymous browsers sorry
   if (!isset($_SERVER['HTTP_REFERER']) || strpos('http://'.$_SERVER['SERVER_NAME'], $_SERVER['HTTP_REFERER']) !== 0) // seems it is an optimization hack: strpos faster than substr+strlen
    exit;
   // compatibility, currently not all the browsers set this
   if (isset($_SERVER['HTTP_ORIGIN']) && strpos('http://'.$_SERVER['SERVER_NAME'], $_SERVER['HTTP_ORIGIN']) !== 0) // seems it is an optimization hack: strpos faster than substr+strlen
    exit;
  }
  // seems like all fine, we can continue with session initialization
     parent::__construct($params);
}

}

In AJAX-controller I do additional check:
Code:
public function my_super_duper_ajax_controller()
{
  // only AJAX-requests allowed to this controller
  if(!$this->input->is_ajax_request() || $this->session->userdata('session_id') === FALSE)
  {
   header('HTTP/1.1 403 Forbidden');
   exit;
  }

  // AJAX-controller code continues here...

}


Digg   Delicious   Reddit   Facebook   Twitter   StumbleUpon  


  Theme © 2014 iAndrew  
Powered By MyBB, © 2002-2021 MyBB Group.