PHP / ajaxcall - approach to prevent abuse or direct access - php

The problem by calling ajax (in my case through jquery) is that the target can be seen in the source of the side. I searched for a solution to prevent abuse and want to ask you what you think of my humble approach.
to know about ajax calls (correct me if i am wrong):
you have to allow direct access to the user because it needs the access like in any regular html rendering.
sessions can be used.
IP tracking could be used since the user is accessing the file and not my script (this would hold for other securing approaches)
out of this i created a script which access the ajaxscript first, gets the time, hashes or encrypts the same time with a good known salt and password and delivers these two values to the user. in the success function i take this 2 values and access the main-script with the next ajaxcall. There i check these values:
Are the time and the encrypted time equal
Did not more than x seconds run after the two ajax calls
I also included a easy to fake $_SERVER['HTTP_X_REQUESTED_WITH' just for additional security, this can easy be spoofed and faken. Instead of delivering the 2 values through GET you could use Session to transport those :).
the index.html
<script>
$(document).ready(function() {
$("#ajaxloadlink").click(function(){
$("#ajaxcontent").load("ajax.php",function(responseText, textStatus, XMLHttpRequest){
// alert(responseText);
var pruf = responseText; // $("#ajaxcontent").html();
var arr = pruf.split('|');
var geturl = "ajax.php?verifyvar="+ arr[1] +"&timedone="+ arr[0];
$("#ajaxcontent").load(geturl);
});
});
});
</script>
<button id="ajaxloadlink">Lade ajax.php mit load()</button>
the processfile ajax.php:
<?php
// the function to use for encryption
define('SALT', 'whateveryouwant');
function encrypt($text)
{
return trim(base64_encode(mcrypt_encrypt(MCRYPT_RIJNDAEL_256, SALT, $text, MCRYPT_MODE_ECB, mcrypt_create_iv(mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_ECB), MCRYPT_RAND))));
}
function decrypt($text)
{
return trim(mcrypt_decrypt(MCRYPT_RIJNDAEL_256, SALT, base64_decode($text), MCRYPT_MODE_ECB, mcrypt_create_iv(mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_ECB), MCRYPT_RAND)));
}
if( isset( $_SERVER['HTTP_X_REQUESTED_WITH'] ) && ( $_SERVER['HTTP_X_REQUESTED_WITH'] == 'XMLHttpRequest' ) )
{
//only internal scripts can be used, fakeable
if(empty($_GET))
{
$time = time();
$verifvar_created = encrypt($time);
echo $time."|".$verifvar_created;
}
else
{
//zweiter Durchlauf
$verifvar = $_GET['verifyvar'];
$timedone = $_GET['timedone'];
//VERIFY
$curtime = time(); //holds also timemax
$timemin = $curtime - 2;
if($timedone <= $curtime && $timedone >= $timemin)
{
echo "COOOL";
//now its an actual request
$verifvar_checked = decrypt($timedone);
if ($verifvar == $verifvar_checked)
{
echo "VERIFIED";
// now process the actual script
// :)
}
}
}
} else
{
echo "no direct access allowed";
}
?>
It would be a honor for me to hear what you think of my approach and to correct the code if you think it has to. For me it works, i allowed 2 seconds between the ajax calls (which is easy to render since it are just 2 words).
Generally all accessible content can be accessed by using curl with correct headers by going through index.html like any regular user would. because in most environments (like php) curl can't access ajaxcalls easily since it can't "click" buttons which is needed in this script. Although in other environments like watir, selenium you can easily fake that too.
So is that for you an additional layer of security?
Thanks for your opinions helping me out. Thanks also for correcting my wrongdoings.
Have a great Day here at SOF 2012!!

To obfuscate things even more, you could make it two (or maybe even more) different server scripts each returning only part of the response, encrypted by a shared key which is available only from the index page. So the javascript code would have to do two different ajax calls, then put the responses together, decrypt it in client side and only then it would be usable.
But this would not help you in defense against Selenium, at it can do anything a user would normally do.

Ajax calls aren't -technically- diffrent than normal POST/GET requests and the target is always has to visible to user/browser, you can't make your application secure by "security through obscurity" approach.
If your goal is limit the request rate you should done that on web server or firewall level. If you want to use php, you can use sessions to identify users and also limit their request rate.
<?php
session_start();
if( !isset($_SESSION['time'])
|| $_SESSION['time'] < ( time() - 60 * 5 )
){
$_SESSION['time' ] = time();
$_SESSION['count'] = 0 ;
}
$_SESSION['count']++ ;
if( $_SESSION['count'] > 10 ){
die("Stop ! You can't make more than 10 requests in 5 Minutes");
}
Bu since sessions use cookies, it's useless to defend your application against http flood.

Related

How to securely get variables from a link?

Suppose a website xyz.com is showing ads from my ad network example.com using JavaScript code:
<script type='text/javascript' src='http://example.com/click.php?id=12345678'></script>
Which shows the ad as:
click.php
<a href="http://example.com/process.php?var1=var1&var2=var2">
<img src="http://example.com/ads/banner.png"/></a>
When the link is clicked it is taken to process.php where I add and subtract balance using some MySQL queries and then redirect to ad's URL.
process.php
$ua = $_SERVER['HTTP_USER_AGENT'];
$ip = $_SERVER['REMOTE_ADDR'];
//invalid click
if($_SERVER['HTTP_REFERER']==null || $_SERVER['HTTP_USER_AGENT']==null) {
header("location: http://example.com");
exit;
}
I want to add to an Unique Session at click.php and retrieve it at process.php to prevent invalid clicks. How do I do that?
Update:
The answer below solves half of the issue but the users are still able to send fake clicks using iframe and img tag as below:
<img src="http://example.com/click.php?id=12345678" height="1px" width="1px"/>
These clicks are still being counted as the request are served by both the pages click.php and process.php
What's the solution for this?
I have got a solution to the problem and it works perfectly:
EDIT:
I have found a solution:
To set the variables using sessions at click.php and sent it to process.php using a random number
click.php
$_SESSION["ip"]=$ip;
$_SESSION["ua"]=$ua;
$rand="".rand(1,9)."".rand(0,9)."".rand(0,9)."".rand(0,9)."".rand(0,9)."".rand(0,9)."";
$_SESSION["hash"]=$rand;
<a href="http://example.com/process.php?hash=$rand">
<img src="http://example.com/ads/banner.png"/></a>
and getting the values from the session at process.php
process.php
$hash=$_GET["hash"];
$ua=$_SESSION["ua"];
$ip=$_SESSION["ip"];
$rand=$_SESSION["hash"];
// Invalid Redirection Protection
if(($hash!=$rand) || ($ip!=$_SERVER['REMOTE_ADDR']) || ($ua!=$_SERVER['HTTP_USER_AGENT'])) {
header("location: http://example.com");
session_destroy();
exit;
}
If I have understood your question, your goal is to ensure that any requests arriving at http://example.com/process.php were from links created by http://example.com/click.php
(note that this only means that anyone trying to subvert your system needs to fetch http://example.com/click.php and extract the relevant data before fetching http://example.com/process.php. It raises the bar a little but it is a long way from being foolproof).
PHP already has a very good sessions mechanism. It would be easy to adapt to propogation via a url embedded in the script output (since you can't rely on cookies being available). However as it depends on writing to storage, its not very scalable.
I would go with a token with a finite number of predictable good states (and a much larger number of bad states). That means using some sort of encryption. While a symmetric cipher would give the easiest model to understand it's more tricky to implement than a hash based model.
With the hash model you would hash the values you are already sending with a secret salt and include the hash in the request. Then at the receiving end, repeat the exercise and compared the generated hash with the sent hash.
To prevent duplicate submissions you'd need to use some other identifier in the request vars - a large random number, the client IP address, the time....
define('SALT','4387trog83754kla');
function mk_protected_url($url)
{
$parts=parse_url($url);
$args=parse_str($parts['query']);
$args['timenow']=time();
$args['rand']=rand(1000,30000);
sort($args);
$q=http_build_query($args);
$args['hash']=sha1(SALT . $q);
$q=http_build_query($args);
return $parts['scheme'] . '://'
.$parts['host'] . '/'
.$parts['path'] . '?' . $q;
}
function chk_protected_url($url)
{
$parts=parse_url($url);
$args=parse_str($parts['query']);
$hash=$args['hash'];
unset($args['hash'];
// you might also want to validate other values in the query such as the age
$q=http_build_query($args);
$check=sha1(SALT . $q);
return ($hash === $check)
}

forge domain for firefox password autocomplete?

When running two different websites, say free.webhost.com/app1 and free.webhost.com/app2, it seems that Firefox has trouble storing different login credentials for both, especially when the same username is used with different passwords. If a user's credentials on the /app1 site are Name and pass1 and on the other site are Name and pass2, then Firefox can only store one of these and will ask to change the password when hopping between them.
I investigated this problem and to my astonishment this seems to be a WONTFIX in the firefox bug repository: https://bugzilla.mozilla.org/show_bug.cgi?id=263387
Is there any way I can workaround this when designing my apps? Like by setting a certain cookie property in PHP or html, or even specify a (fake) different domain name, so that firefox no longer considers free.webhost.com/app1 and free.webhost.com/app2 as the same website for password storage (and can thus store a different password with the same username for both sites)?
No, there is no workaround or trick for this. Deploy your apps to different domains - even different subdomains (e.g. app1.example.com and app2.example.com) will do.
We need a custom saver. I'm going to try be short and concise.
This is very useful if you don't want the browser saver. I think it can have some applications.
THE BASIC
I suggest in the PHP we use different cookies to save the session with session_name or session.name directive. For each site we must set a session name.
In the HTML we should use different inputs name, so the app1 input will be <input type='email' name='email_app1' /> and app2 email_app2. We also can disable the autocomplete.
The data is saved locally encrypted with AES. For this we can get CryptoJS.
We also want to have salt hash in the client.
THE CONCEPT (summarized):
Save locally the password encrypted. It is returned by the login
controller. Of course if the user wants.
Save a salt which changes in each login. Of course if the user wants.
When the user return to the login page, the JavaScript checks if there
is a salt and it sends it to server. The PHP returns the passphrase and JavaScript decrypts the local password.
the sample code:
In the controller:
// I use functions in the controller like example
public function getLoginPage(){
// it prints the html and js to login using the basics how i have said
}
// salt is sended by the JavaScript
public function getPassphrase( $salt, $username ){
$passPhrase = get_passphrase_from_salt( $salt, $username, Request::IP() );
return $passPhrase;
}
// It is to get the salt
public function getSalt( $username, $password ){
$user = get_user( $username, $password );
// if valid user...
$passphrase = random_string();
$salt = random_string();
$encrypted = encrypt( $password, md5($passphrase) );
save_in_table_salt( $salt, $passphrase, $username, Request::IP() );
// it prints a JSON like example
return json_encode( array( 'salt' => $salt, 'encrypted' => $encrypted) );
}
// ... Normal login etc you could change the salt and reset in the client
In the view we put the JavaScript logic. I used localstorage but I think it's not important.
// in login page
window.onload = function(){
if( localStorage.getItem('salt') !== null ) { // the data is saved
// Get the passphrase
ajax_call('post', 'getPassphrase', {
salt: localStorage.getItem('salt'),
username: localStorage.getItem('username')
}, function( passphrase ){
// It sets the inputs values!
document.getElementById('username_app1').value = localStorage.getItem('username');
document.getElementById('password_app1').value = decrypt( localStorage.getItem('password'), CryptoJS.MD5(passphrase) );
});
}
};
// it captures the submit action
document.getElementById('login_form').onsubmit = function(){
// it asks to user if he wants save locally the credentials
if( localStorage.getItem('salt') === null
&& confirm('Do you want save credentials?') ){
var form = this;
// get salt
ajax_call('post', 'getSalt', {
user: document.getElementById('username_app1').value,
password: document.getElementById('password_app1').value
}, function( object ){
localStorage.setItem('salt', object.salt);
localStorage.setItem('password', object.encrypted);
localStorage.setItem('username', document.getElementById('username_app1').value );
form.submit(); // now yes
});
return false; // it prevents submit
}
};
You must know that the code is a sample. Some functions don't exists and it's only to be understood. We need more conditions and logic to do it works.
UPDATED: Now works with multiple computers and IP security and more!
There is no workaround for this as internal credential storage in Firefox is organized per domain, not per URL.
Even changing Name or ID for input HTML controls or Form tag will not affect this.
Only solution is to host your application on different (sub)domains.
Probably the best solution here would be to create 2 different virtual host for your app.
Like one for webhost.com and one for free.webhost.com.
How To Set Up Apache Virtual Hosts on Ubuntu 12.04 LTS
Hope this help!!
If your are having problem on setting up your virtual host in your server let me know.
Note:You need to create your DNS entry to access the new host you created or you need to add a record to the host file of your system from where you are browsing the site.

Update database using JQuery ajax.Post()

Help! I'm writing some code to update a mySQL database using similar to the code below:-
$.post('http://myURL.com/vote.php?personID=' + personID + '&eventID=123');
The vote.php code takes the querystring values and inserts a record into a database with those values in it.
This kind of code is working fine, but I've realised the problem is that people could just type something like:
http://myURL.com/vote.php?personID=5&eventID=123
into their address bar and essentially spam the app...
Is there a straightforward way I can ensure this doesn't happen? I'm reasonably new to these technologies so not aware of how everything works or fits together, but I'm learning fast so any pointers would be super useful.
It is not a good idea to use GET parameters for data that goes to a database. Generally, you want to use POST parameters which are not visible in the URL. So instead of :
$.post('http://myURL.com/vote.php?personID=' + personID + '&eventID=123');
You would do it like this :
$.post('http://myURL.com/vote.php', { "personID" : personID, "eventID" : 123 });
And in your PHP script, you would access your data with the $_POST array like this :
$personID = $_POST['personID'];
$eventID = $_POST['eventID'];
However, don't forget to properly filter input before saving to the database to prevent bad things like SQL Injection.
This is not a silver bullet : spam will still be possible because any HTTP client will be able to send a post request to your site. Another thing you can look at is Security Tokens to make it even less vulnerable to spam. Or implement a system that limits the number of request/minute/user... but I'm getting too far from the original question.
Correct syntax of $.post is
$.post(url,data_to_send,callback_function)
By using this method your user will never be able to damage your site.Use like
$.post('http://myURL.com/vote.php',{"personID":personID,"eventID":123);
Whether you're using POST or GET, you could always consider signing important fields in your page by using hash_hmac. This prevents people from changing its value undetected by adding a signature that no one else can guess.
This also makes CSRF more difficult, though not impossible due to fixation techniques. It's just yet another technique that can be put in place to make it more difficult for "fiddlers".
The following function adds a salt and signature to a given person id to form a secured string.
define('MY_SECRET', 'an unguessable piece of random text');
function getSecurePersonId($personId)
{
$rnd = uniqid("$personId-", true);
$sig = hash_hmac('sha1', $rnd, MY_SECRET);
return "$rnd-$sig";
}
You would pass the output of getSecuredPersonId() to JavaScript to pass as data in the $.post() or $.get(); posting would be recommended btw.
When the form is submitted your person id would end up in either $_GET['personID'] or $_POST['personID'] depending on the request method. To validate the given value, you run it through this function:
function validateSecurePersonId($securePersonId)
{
if (3 != count($parts = explode('-', $securePersonId))) {
return false;
}
// reconstruct the signed part
$rnd = "{$parts[0]}-{$parts[1]}";
// calculate signature
$sig = hash_hmac('sha1', $rnd, MY_SECRET);
// and verify against given signature
return $sig === $parts[2] ? $parts[0] : false;
}
If the value is properly signed, it will return the original person id that you started out with. In case of failure it would return false.
Small test:
$securePersonId = getSecurePersonId(123);
var_dump($securePersonId);
if (false === validateSecurePersonId($securePersonId)) {
// someone messed with the data
} else {
// all okay
}

Is it possible to block cookies from being set using Javascript or PHP?

A lot of you are probably aware of the new EU privacy law, but for those who are not, it basically means no site operated by a company resident in the EU can set cookies classed as 'non-essential to the operation of the website' on a visitors machine unless given express permission to do so.
So, the question becomes how to best deal with this?
Browsers obviously have the ability to block cookies from a specific website built in to them. My question is, is there a way of doing something similar using JS or PHP?
i.e. intercept any cookies that might be trying to be set (including 3rd party cookies like Analytics, or Facebook), and block them unless the user has given consent.
It's obviously possible to delete all cookies once they have been set, but although this amounts to the same thing as not allowing them to be set in the first place, I'm guessing that it's not good enough in this case because it doesn't adhere to the letter of the law.
Ideas?
I'm pretty interested in this answer too. I've accomplished what I need to accomplish in PHP, but the JavaScript component still eludes me.
Here's how I'm doing it in PHP:
$dirty = false;
foreach(headers_list() as $header) {
if($dirty) continue; // I already know it needs to be cleaned
if(preg_match('/Set-Cookie/',$header)) $dirty = true;
}
if($dirty) {
$phpversion = explode('.',phpversion());
if($phpversion[1] >= 3) {
header_remove('Set-Cookie'); // php 5.3
} else {
header('Set-Cookie:'); // php 5.2
}
}
Then I have some additional code that turns this off when the user accepts cookies.
The problem is that there are third party plugins being used in my site that manipulate cookies via javascript and short of scanning through them to determine which ones access document.cookie - they can still set cookies.
It would be convenient if they all used the same framework, so I might be able to override a setCookie function - but they don't.
It would be nice if I could just delete or disable document.cookie so it becomes inaccessible...
EDIT:
It is possible to prevent javascript access to get or set cookies.
document.__defineGetter__("cookie", function() { return '';} );
document.__defineSetter__("cookie", function() {} );
EDIT 2:
For this to work in IE:
if(!document.__defineGetter__) {
Object.defineProperty(document, 'cookie', {
get: function(){return ''},
set: function(){return true},
});
} else {
document.__defineGetter__("cookie", function() { return '';} );
document.__defineSetter__("cookie", function() {} );
}
I adapted Michaels codes from here to come up with this.
Basically it uses the defineGetter and defineSetter methods to set all the cookies on the page and then remove the user specified ones, this role could of course also be reversed if this is what you are aiming for.
I have tested this with third party cookies such as Google Analytics and it appears to work well (excluding the __utmb cookie means I am no longer picked up in Google Analytics), maybe you could use this and adapt it to your specific needs.
I've included the part about if a cookies name is not __utmb for your reference, although you could easily take these values from an array and loop through these that way.
Basically this function will include all cookies except those specified in the part that states if( cookie_name.trim() != '__utmb' ) { all_cookies = all_cookies + cookies[i] + ";"; }
You could add to this using OR or AND filters or pull from an array, database, user input or whatever you like to exclude specific ones (useful for determining between essential and non-essential cookies).
function deleteSpecificCookies() {
var cookies = document.cookie.split(";");
var all_cookies = '';
for (var i = 0; i < cookies.length; i++) {
var cookie_name = cookies[i].split("=")[0];
var cookie_value = cookies[i].split("=")[1];
if( cookie_name.trim() != '__utmb' ) { all_cookies = all_cookies + cookies[i] + ";"; }
}
if(!document.__defineGetter__) {
Object.defineProperty(document, 'cookie', {
get: function(){return all_cookies; },
set: function(){return true},
});
} else {
document.__defineGetter__("cookie", function() { return all_cookies; } );
document.__defineSetter__("cookie", function() { return true; } );
}
}
You can not disable it completely but you can override the default setting with .htaccess
Try
SetEnv session.use_cookies='0';
If it is optional for some users don't use .htaccess
if(!$isAuth)
{
ini_set('session.use_cookies', '0');
}
A little bit old but I think you deserve a answer that works:
Step 1: Don't execute the third party script code.
Step 2: Show the cookie banner.
Step 3: Wait until user accepts, now you can execute the third party script code..
Worked for me.
How about not paying attention to hoaxes?
Aside from the fact that this is old news, the text clearly says that it only applies to cookies that are not essential to the site's function. Meaning session cookies, a shopping basket, or anything that is directly related to making the site work is perfectly fine. Anything else (tracking, stats, etc.) are "not allowed" without permission.

How to create and use nonces

I am running a website, and there is a scoring system that gives you points for the number of times you play a game.
It uses hashing to prove the integrity of http request for scoring so users cannot change anything, however as I feared might happen, someone figured out that they didn't need to change it, they just needed to get a high score, and duplicate the http request, headers and all.
Previously I'd been prohibited from protecting against this attack because it was considered unlikely. However, now that it has happened, I can. The http request originates from a flash game, and then is validated by php and php enters it into the database.
I'm pretty sure nonces will solve the issue, but I'm not exactly sure how to implement them. What is a common, and secure way of setting up a nonce system?
It's actually quite easy to do... There are some libraries out there to do it for you:
PHP Nonce Library
OpenID Nonce Library
Or if you want to write your own, it's pretty simple. Using the WikiPedia page as a jumping off point, In pseudo-code:
On the server side, you need two client callable functions
getNonce() {
$id = Identify Request //(either by username, session, or something)
$nonce = hash('sha512', makeRandomString());
storeNonce($id, $nonce);
return $nonce to client;
}
verifyNonce($data, $cnonce, $hash) {
$id = Identify Request
$nonce = getNonce($id); // Fetch the nonce from the last request
removeNonce($id, $nonce); //Remove the nonce from being used again!
$testHash = hash('sha512',$nonce . $cnonce . $data);
return $testHash == $hash;
}
And on the client side:
sendData($data) {
$nonce = getNonceFromServer();
$cnonce = hash('sha512', makeRandomString());
$hash = hash('sha512', $nonce . $cnonce . $data);
$args = array('data' => $data, 'cnonce' => $cnonce, 'hash' => $hash);
sendDataToClient($args);
}
The function makeRandomString really just needs to return a random number or string. The better the randomness, the better the security... Also note that since it's fed right into a hash function, the implementation details don't matter from request to request. The client's version and the server's version don't need to match. In fact, the only bit that needs to match 100% is the hash function used in hash('sha512', $nonce . $cnonce . $data);... Here's an example of a reasonably secure makeRandomString function...
function makeRandomString($bits = 256) {
$bytes = ceil($bits / 8);
$return = '';
for ($i = 0; $i < $bytes; $i++) {
$return .= chr(mt_rand(0, 255));
}
return $return;
}
Nonces are a can of worms.
No, really, one of the motivations for several CAESAR entries was to design an authenticated encryption scheme, preferably based on a stream cipher, that is resistant to nonce reuse. (Reusing a nonce with AES-CTR, for example, destroys the confidentiality of your message to the degree a first year programming student could decrypt it.)
There are three main schools of thought with nonces:
In symmetric-key cryptography: Use an increasing counter, while taking care to never reuse it. (This also means using a separate counter for the sender and receiver.) This requires stateful programming (i.e. storing the nonce somewhere so each request doesn't start at 1).
Stateful random nonces. Generating a random nonce and then remembering it to validate later. This is the strategy used to defeat CSRF attacks, which sounds closer to what is being asked for here.
Large stateless random nonces. Given a secure random number generator, you can almost guarantee to never repeat a nonce twice in your lifetime. This is the strategy used by NaCl for encryption.
So with that in mind, the main questions to ask are:
Which of the above schools of thought are most relevant to the problem you are trying to solve?
How are you generating the nonce?
How are you validating the nonce?
Generating a Nonce
The answer to question 2 for any random nonce is to use a CSPRNG. For PHP projects, this means one of:
random_bytes() for PHP 7+ projects
paragonie/random_compat, a PHP 5 polyfill for random_bytes()
ircmaxell/RandomLib, which is a swiss army knife of randomness utilities that most projects that deal with randomness (e.g. fir password resets) should consider using instead of rolling their own
These two are morally equivalent:
$factory = new RandomLib\Factory;
$generator = $factory->getMediumStrengthGenerator();
$_SESSION['nonce'] [] = $generator->generate(32);
and
$_SESSION['nonce'] []= random_bytes(32);
Validating a Nonce
Stateful
Stateful nonces are easy and recommended:
$found = array_search($nonce, $_SESSION['nonces']);
if (!$found) {
throw new Exception("Nonce not found! Handle this or the app crashes");
}
// Yay, now delete it.
unset($_SESSION['nonce'][$found]);
Feel free to substitute the array_search() with a database or memcached lookup, etc.
Stateless (here be dragons)
This is a hard problem to solve: You need some way to prevent replay attacks, but your server has total amnesia after each HTTP request.
The only sane solution would be to authenticate an expiration date/time to minimize the usefulness of replay attacks. For example:
// Generating a message bearing a nonce
$nonce = random_bytes(32);
$expires = new DateTime('now')
->add(new DateInterval('PT01H'));
$message = json_encode([
'nonce' => base64_encode($nonce),
'expires' => $expires->format('Y-m-d\TH:i:s')
]);
$publishThis = base64_encode(
hash_hmac('sha256', $message, $authenticationKey, true) . $message
);
// Validating a message and retrieving the nonce
$decoded = base64_decode($input);
if ($decoded === false) {
throw new Exception("Encoding error");
}
$mac = mb_substr($decoded, 0, 32, '8bit'); // stored
$message = mb_substr($decoded, 32, null, '8bit');
$calc = hash_hmac('sha256', $message, $authenticationKey, true); // calcuated
if (!hash_equals($calc, $mac)) {
throw new Exception("Invalid MAC");
}
$message = json_decode($message);
$currTime = new DateTime('NOW');
$expireTime = new DateTime($message->expires);
if ($currTime > $expireTime) {
throw new Exception("Expired token");
}
$nonce = $message->nonce; // Valid (for one hour)
A careful observer will note that this is basically a non-standards-compliant variant of JSON Web Tokens.
One option (which I mentioned in comment) is recording gameplay and replay it in secure environment.
The other thing is to randomly, or at some specified times, record some seemingly innocent data, which later can be used to validate it on server (like suddenly live goes from 1% to 100%, or score from 1 to 1000 which indicate cheat). With enough data it might just not be feasible for cheater to try to fake it. And then of course implement heavy banning :).
This very simple nonce changes every 1000 seconds (16 minutes)
and can be used for avoiding XSS where you are posting data to and from the same application. (For example if you are in a single page application where you are posting data via javascript. Note that you must have access to the same seed and nonce generator from the post and the receiving side)
function makeNonce($seed,$i=0){
$timestamp = time();
$q=-3;
//The epoch time stamp is truncated by $q chars,
//making the algorthim to change evry 1000 seconds
//using q=-4; will give 10000 seconds= 2 hours 46 minutes usable time
$TimeReduced=substr($timestamp,0,$q)-$i;
//the $seed is a constant string added to the string before hashing.
$string=$seed.$TimeReduced;
$hash=hash('sha1', $string, false);
return $hash;
}
But by checking for the previous nonce, the user will only be bothered if he waited more than 16.6 minutes in worst case and 33 minutes in best case. Setting $q=-4 will give the user at least 2.7 hours
function checkNonce($nonce,$seed){
//Note that the previous nonce is also checked giving between
// useful interval $t: 1*$qInterval < $t < 2* $qInterval where qInterval is the time deterimined by $q:
//$q=-2: 100 seconds, $q=-3 1000 seconds, $q=-4 10000 seconds, etc.
if($nonce==$this->makeNonce($seed,0)||$nonce==$this->makeNonce($seed,1)) {
//handle data here
return true;
} else {
//reject nonce code
return false;
}
}
The $seed, could be the any function call or user name, etc. used in the process.
It is not possible to prevent cheating. You can only make it more difficult.
If someone came here looking for a PHP Nonce Library: I recommend not using the first one given by ircmaxwell.
The first comment on the website describes a design flaw:
The nonce is good for one certain time window, i.e. the nearer the
user gets to the end of that windows the less time he or she has to
submit the form, possibly less than one second
If you are looking for a way to generate Nonces with a well-defined lifetime, have a look at NonceUtil-PHP.
Disclaimer: I am the author of NonceUtil-PHP

Categories