allnodcoms
allnodcoms

Reputation: 1262

Can you tell, via PHP, whether an ajax call came from a page or the console?

I'm updating a database via PHP with data that's being sent via ajax. Is there a way to tell whether the script that is sending the data is called by the page on which it is included (remotely hosted), or just being hacked into the JS Console by someone who's "inspected my elements" and trying to pull a fast one?

Thanks in advance...

Danny

Upvotes: 1

Views: 89

Answers (2)

user3788486
user3788486

Reputation: 88

There really is no way of telling between either of them, but you can make the job much harder to do.
But since you say that 'it won't start wars', working off of that, there are a few ways of 'securing' it.

Step 1 : Creating 'Verification' calls
If you aren't already, the very first step would be to implement a few preliminary AJAX calls that retrieve certain variables which are later used in the calls that follow, for example:

  1. Call #1 Retrieves Security-Token
  2. Call #2 Creates a cookie Security-Token-2
  3. Call #3 Call to your php script with Security-Token encrypted with Security-Token-2

What your page would then do, would decrypt the sent text with the 'token' stored in the cookie and use that.

Step 2 : Adding extra logic into javascript
You can add some encoding-decoding logic into the javascript,
I'm not saying this is going to be hard to break, but It might be tough, especially if you obfuscate your code (We all know obfuscation is no good, but bear with me)

Step 3 : Don't keep any names
Another thing you can do is remove all the names from the AJAX variables, or better yet, the names can be different every time.
If you want to go even further, you can encrypt the names, and plus to the encryption add a component of randomness by introducing an IV, and storing the IV in the cookies (maybe even encoded for added security).

(EDIT) Found the 'dynamic name generation' solution I was looking for:
Dynamic Field Names in PHP
The solution was initially designed to fight spambots which 'autofill' certain fields, and if the field names look random it doesn't know which fields are 'traps', however you could use it to generate the names for your AJAX calls.

In the end though, it is always possible to crack, all one needs is enough time and money.

Upvotes: 2

user4925382
user4925382

Reputation:

This is a youtube guide by phpcademy (now codecourse) that throughly explains how to prevent CSRF (Cross Site Request Forgery) in PHP.

It involves generating a new random token every time a form is submitted. Afterwards you check if a token has been posted. If not, the request is not authentic.

EDIT: you needn't be worried about people seeing the token when inspecting the page, as you have your own (server side) way of validating your token.

Upvotes: 1

Related Questions