Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I restrict access to some PHP pages only from pages within my website?

Tags:

ajax

security

php

I have in my website a PHP page which retrieves data from my database to be presented in my website. This page is called via AJAX. How can I restrict the access to it only from pages within my website so users who wants to abuse it and get this data not from the website (e.g. posting HTTP request from their server) itself won't be able to do so ?

like image 855
Yossi Avatar asked May 06 '10 21:05

Yossi


2 Answers

This is what I do,

  1. On your website, create a secret string. I use the HMAC($_SERVER['REMOTE_ADDR'], key).
  2. Write the secret in a Javascript var.
  3. On the AJAX call, pass this string as a parameter.
  4. On the AJAX server, do the hash again. If it's matches the parameter, the call is from your page.

EDIT: Code examples,

In your website, you do this,

$key = 'supersecretkey'; // This is your security, don't expose this
$nonce = rand();
$timestamp = time();
$signature = hash_hmac('sha1', $_SERVER['REMOTE_ADDR'] . $nonce . $timestamp, $key);

Print out the vars to the page,

<script type="text/javascript">
<?php
echo "  var signature = '" . $signature . "';\n";
echo "  var nonce = '" . $nonce . "';\n";   
echo "  var timestamp = '" . $timestamp . "';\n";
?>
</script>

When you make AJAX call, pass the 3 parameters to the server,

  http://example.com?signature=...&nonce=...&timestamp=...

On the AJAX server, do the calculation again,

$key = 'supersecretkey'; // This is your security, don't expose this
$nonce = $_REQUEST['nonce'];
$timestamp = $_REQUEST['timestamp'];
$signature = hash_hmac('sha1', $_SERVER['REMOTE_ADDR'] . $nonce . $timestamp, $key);

if ($signature == $_REQUEST['signature'])
   // the call if from my page.

You can also chech timestamp for currency and nonce for replay (need session or data store).

like image 130
ZZ Coder Avatar answered Oct 05 '22 10:10

ZZ Coder


This can not really be done if stated as above, you would need to redesign and implement some kind of authentication scheme, but even that can be emulated. The short answer is that if a web browser can access it then anything can access it as long as it pretends to be a browser.

There are things you could do to make it harder for someone, like verifying HTTP header fields such as Referer and User-Agent, and implementing session verification in the AJAX calls.

like image 43
kb. Avatar answered Oct 05 '22 12:10

kb.