Both client-side and server-side validation for my game - javascript

I'm making a multiplayer game, where players (1 up to 4) put items on the board (multiple items per move are permitted) one by another. The game is ajax-based. The rules of placing items on the board are pretty complicated, plenty of combinations are forbidden.
What I want to achieve is performing moves validations immediately when player places his item on the board, so there's no lag. He knows if his move is valid or not in no time. Then, the same rules are being checked on server-side, once the move is submitted. This is of course for security reasons, to deal with ajax spoofing. What I'm sending in the request is just a map of items IDs and fields indexes. On the server I'm checking tons of stuff, including whether all those items belong to the player who is permitted to move now and if those items can be put on these particular fields.
I'm thinking about the best practice to validate fields indexes. Now, I have two completely separate scripts, JavaScript one and PHP one. Is there any way to make it more flexible, so if I decide to change the rules, I could change it on both sides? I know I could do some rules mapping object and then write interpreters for both sides, but those rules are too complicated to work with any map like that.

Just a thought.
You could write all your game rule logic in a separate Javascript file in an easy to consume way.. Since this can be run on the client side that problem is out of the way.. And then using this (se link) PHP functionality call the same javascript code from within PHP and test moves for validity.
http://php.net/manual/en/v8js.examples.php
This way you can write your rules once and run them on both sides without having to rewrite them.
If you cant do something like this I would make the server calculate all possible moves for each game piece at the start of each round and send them to the client to present as possible actions. This way you client has no game logic but can still present valid moves without making queries for each one.
This also has the benefit of only having your rules on the server side and not letting people in to the details of how you are checking them.

Related

JavaScript vs PHP in sorting an array

I am getting the information from the user. Then I am to sort the information (Alphanumerically), and give it back to the user again, hence not saving it to the database.
I am able to use either JavaScript (you could even count on jQuery), or PHP to do the sorting. Since the data might contain many lines, I am wondering about approaches below for the sorting:
let's say I tokenize all the lines using an array called lines
in JavaScript lines.sort();
in PHP sort($lines);
I am very keen to know if client-side or server-side would be doing this any differently, mainly in terms of speed. Also, if accuracy is important, then would they be any different at all? Please explain why.
1) jQuery sort() is speedy as it has client side load.
2) For server side sorting we need to find from whole data not only from display in current page for pagination.
For Server side sorting is best for:
Large data set
Faster initial page load
Accessibility for those not running javascript
Client side sorting is best for:
Small data set
Faster subsequent page loads
Ability to let the user sort without loading page
That makes difference between server side sorting and client side.
It would depend on the situation. Javascript means client side load. So if the client has a slow system it might take longer. But server side means you would have to get the data into php (either database or by request etc.) and after the sort back to the client.
One other thing to think about is that php is controlled. You can assure the output is the same. In Javascript it should be the same on every system. But different browsers could generate different results on sort.

How to secure javascript based multiplayers games

First of all, I understand this question might be off topic and not in scope of stackoverflow but I still decided to ask since I don't know any other better place.
My question is, if I make an online game based on game engines written in javascript eg CreateJS. The game code is going to be run on the clients machine and since javascript is interpreted, it is viewable by the client.
So if a mutliplayer game is being made where users can compete against each other, what measure are taken to prevent cheating. I'm asking because since the game source is viewable, anyone can simple modify the game source and potentially cheat.
Edit: For the idea of the game, lets make one up which is very simple. Imagine we are making a game like FlappyBird or a game where the further you go in a linear map, the more point you stack up.
At the end of the game, your score is submited via a http request.
Now what is stopping a user from editing the game which causes the points to stack up 10x faster? causing a higher score to be submited?
Edit 2: Or what is stopping the users from submitting a request containing false scores via cURL without ever having to play the game?
Multiplayer games prevent cheating usually by simply verifying the game steps, rather than just the complete game output. Since all other players need to know what other players do, you will have to tell the server every step of the way and let the server "simulate" the game and check if these steps are actually valid or not. The only way to cheat in this case is by writing an AI in your browser that will then produce a feasible set of steps coming to a good result.
You also will have to send these player steps to everyone else. Since in a continuous environment players can perform so many actions per second (e.g. move and turn), you want to make sure to minimize the amount of updates to be sent. E.g. when walking in a straight line, World of Warcraft,for example, only sends an update every 500ms. They might also do not necessarily simulate and verify every single step you take, but only every X steps to avoid people running through walls or jumping over entire buildings etc.
Please note that any fast-paced game will not work well when using AJAX calls. Just setting up a connection can take many times as long as just sending a packet through an established connection. That is why you want to use Websockets in that case.
Of course, minifying and obfuscating your code will put some stones in the ways of a cheater, but depending on the vulnerabilities of your system, they might do very little, since it is usually very easy to find the code that takes care of sending and receiving packets or other core aspects of your game, no matter how well obfuscated it is.
Since you cannot believe your clients, you should make an authoritative server and dumb clients model;
That articles are full of gems for who want implements an multiplayer game
the game state is managed by the server alone. Clients send their
actions to the server. The server updates the game state periodically,
and then sends the new game state back to clients, who just render it
on the screen.
From your point of view, what happened is that you pressed the right
arrow but nothing happened for a tenth of a second; then your
character finally moved one square to the right. This perceived lag
between your inputs and its consequences may not sound like much, but
it’s noticeable – and of course, a lag of half a second isn’t just
noticeable, it actually makes the game unplayable.
So you must implement a Client-side prediction and a Server reconciliation
If you develop a "multiplayer" based game, than you should persist the data on a server, centralized, accessed by ajax within your game.
And you're right, someone could potentially "cheat" by overwriting your code with firebug for example or Greasemonkey before you send your data via a http request (ajax).
In order to prevent this you could load your ajax code for saving data dynamically. You can only prevent it by making it more difficult to overwrite your code. Use for example one-way-token in a virtual session, like the token used in OAuth, like a ticket for a ajax-call. Every other call without the right token should be refuted.

Prevent user from tampering score [duplicate]

I'm going to be developing an online arcade for HTML5/Javascript games written in a to-be-released IDE.
The game will use Ajax requests to the server to record scores when people play these games.
I theoretically have complete control over the design of this, including the mechanics of the code that logs the high scores, game code, everything.
I know it's never impossible to hack client side games such as this or spoof high scores, but I want to make it difficult enough so that anyone competent enough wont be bothered enough to do it (wishful thinking).
I've read:
How can you prevent bogus high scores from appearing on a global high score list?
Which is a slightly different question as this is HTML/JS specific.
My initial idea is that the ajax request checks the source of the request is from the correct location, which is a simple and effective block for most hacking attempts.
As the previous answer stated you cannot trust the client, therefore your best bet is to split a game up into levels of some sort and have the server control level progression. If the server is tracking each client and their progression it can limit the range of scores achievable. This makes it more tedious to cheat as the client has to simulate going through each level and indicate achievement within the correct score range.
Each time you serve the page include a randomly generated key and on the server associate the key with the users session.
pass this key around and manipulate it in obscure ways at various points in your game script.
generate a checksum derived from the score and the manipulated key.
send the checksum to the server along with the score
validate the checksum on the server
obfuscate the script
It won't stop a dedicated hacker though.
Here is one way that is both pretty simple (though not trivial) to implement and very hard to hack and not so simple to hack.
On the server side, have list of let's say 1000 items stored in either text file or database.
Each item will be unique GUID or other unique long string, let's call each item key.
Now, when you send AJAX request send one of those keys as well.. it can be random from the list or by incrementing index it doesn't matter.
Now comes the nice part: after one single "use" of each key (meaning the server got request with that key and responded to it), remove the key from the file/database. If the server get request with key that does not exist in the list, of course throw error or return "no hacking" string.
When the list becomes empty, recreate it with fresh unique keys.
This way the first request with the real key should succeed as usual, but if the user will try calling again to the same request exactly, it will fail. Guessing the keys is also very hard assuming those are long random values.
Like any other way, it's flawed due to depending on client side code that can be spoofed by those who know how. But as it's not common, it will be harder for the common folk to find how this works and hack it.
This doesn't work for all games but...
If you log all control input on every frame, and also log the RNG seed at the start of the level, it may be possible to re-run the level by replaying the controller input and get the exact same sequence of events. This can be used to verify that the game was actually played and the score was not just made up. It will be expensive to verify every game, but there are other options, e.g. only verify a game if the score would be in the top 100, or test random games and disable the accounts if verification fails.
Then sit back and watch as the cheaters start using robots to play for them instead, which is even harder to defend against.
Add a md5 hash of the highscore code and compare it on the server. But do not the md5 exactly of the highscore, not on all chars of the highscore only some of the chars, like second to last char. In this case it will be difficult to see what the md5 consists of, when just tracing the ajax calls.

Preventing cheating for on-line arcade high score board

I'm going to be developing an online arcade for HTML5/Javascript games written in a to-be-released IDE.
The game will use Ajax requests to the server to record scores when people play these games.
I theoretically have complete control over the design of this, including the mechanics of the code that logs the high scores, game code, everything.
I know it's never impossible to hack client side games such as this or spoof high scores, but I want to make it difficult enough so that anyone competent enough wont be bothered enough to do it (wishful thinking).
I've read:
How can you prevent bogus high scores from appearing on a global high score list?
Which is a slightly different question as this is HTML/JS specific.
My initial idea is that the ajax request checks the source of the request is from the correct location, which is a simple and effective block for most hacking attempts.
As the previous answer stated you cannot trust the client, therefore your best bet is to split a game up into levels of some sort and have the server control level progression. If the server is tracking each client and their progression it can limit the range of scores achievable. This makes it more tedious to cheat as the client has to simulate going through each level and indicate achievement within the correct score range.
Each time you serve the page include a randomly generated key and on the server associate the key with the users session.
pass this key around and manipulate it in obscure ways at various points in your game script.
generate a checksum derived from the score and the manipulated key.
send the checksum to the server along with the score
validate the checksum on the server
obfuscate the script
It won't stop a dedicated hacker though.
Here is one way that is both pretty simple (though not trivial) to implement and very hard to hack and not so simple to hack.
On the server side, have list of let's say 1000 items stored in either text file or database.
Each item will be unique GUID or other unique long string, let's call each item key.
Now, when you send AJAX request send one of those keys as well.. it can be random from the list or by incrementing index it doesn't matter.
Now comes the nice part: after one single "use" of each key (meaning the server got request with that key and responded to it), remove the key from the file/database. If the server get request with key that does not exist in the list, of course throw error or return "no hacking" string.
When the list becomes empty, recreate it with fresh unique keys.
This way the first request with the real key should succeed as usual, but if the user will try calling again to the same request exactly, it will fail. Guessing the keys is also very hard assuming those are long random values.
Like any other way, it's flawed due to depending on client side code that can be spoofed by those who know how. But as it's not common, it will be harder for the common folk to find how this works and hack it.
This doesn't work for all games but...
If you log all control input on every frame, and also log the RNG seed at the start of the level, it may be possible to re-run the level by replaying the controller input and get the exact same sequence of events. This can be used to verify that the game was actually played and the score was not just made up. It will be expensive to verify every game, but there are other options, e.g. only verify a game if the score would be in the top 100, or test random games and disable the accounts if verification fails.
Then sit back and watch as the cheaters start using robots to play for them instead, which is even harder to defend against.
Add a md5 hash of the highscore code and compare it on the server. But do not the md5 exactly of the highscore, not on all chars of the highscore only some of the chars, like second to last char. In this case it will be difficult to see what the md5 consists of, when just tracing the ajax calls.

What is the best way to filter spam with JavaScript?

I have recently been inspired to write spam filters in JavaScript, Greasemonkey-style, for several websites I use that are prone to spam (especially in comments). When considering my options about how to go about this, I realize I have several options, each with pros/cons. My goal for this question is to expand on this list I have created, and hopefully determine the best way of client-side spam filtering with JavaScript.
As for what makes a spam filter the "best", I would say these are the criteria:
Most accurate
Least vulnerable to attacks
Fastest
Most transparent
Also, please note that I am trying to filter content that already exists on websites that aren't mine, using Greasemonkey Userscripts. In other words, I can't prevent spam; I can only filter it.
Here is my attempt, so far, to compile a list of the various methods along with their shortcomings and benefits:
Rule-based filters:
What it does: "Grades" a message by assigning a point value to different criteria (i.e. all uppercase, all non-alphanumeric, etc.) Depending on the score, the message is discarded or kept.
Benefits:
Easy to implement
Mostly transparent
Shortcomings:
Transparent- it's usually easy to reverse engineer the code to discover the rules, and thereby craft messages which won't be picked up
Hard to balance point values (false positives)
Can be slow; multiple rules have to be executed on each message, a lot of times using regular expressions
In a client-side environment, server interaction or user interaction is required to update the rules
Bayesian filtering:
What it does: Analyzes word frequency (or trigram frequency) and compares it against the data it has been trained with.
Benefits:
No need to craft rules
Fast (relatively)
Tougher to reverse engineer
Shortcomings:
Requires training to be effective
Trained data must still be accessible to JavaScript; usually in the form of human-readable JSON, XML, or flat file
Data set can get pretty large
Poorly designed filters are easy to confuse with a good helping of common words to lower the spamacity rating
Words that haven't been seen before can't be accurately classified; sometimes resulting in incorrect classification of entire message
In a client-side environment, server interaction or user interaction is required to update the rules
Bayesian filtering- server-side:
What it does: Applies Bayesian filtering server side by submitting each message to a remote server for analysis.
Benefits:
All the benefits of regular Bayesian filtering
Training data is not revealed to users/reverse engineers
Shortcomings:
Heavy traffic
Still vulnerable to uncommon words
Still vulnerable to adding common words to decrease spamacity
The service itself may be abused
To train the classifier, it may be desirable to allow users to submit spam samples for training. Attackers may abuse this service
Blacklisting:
What it does: Applies a set of criteria to a message or some attribute of it. If one or more (or a specific number of) criteria match, the message is rejected. A lot like rule-based filtering, so see its description for details.
CAPTCHAs, and the like:
Not feasible for this type of application. I am trying to apply these methods to sites that already exist. Greasemonkey will be used to do this; I can't start requiring CAPTCHAs in places that they weren't before someone installed my script.
Can anyone help me fill in the blanks? Thank you,
There is no "best" way, especially for all users or all situations.
Keep it simple:
Have the GM script initially hide all comments that contain links and maybe universally bad words (F*ck, Presbyterian, etc.). ;)
Then the script contacts your server and lets the server judge each comment by X criteria (more on that, below).
Show or hide comments based on the server response. In the event of a timeout, show or reveal based on a user preference setting ("What to do when the filter server is down? (show/hide comments with links) ).
That's it for the GM script; the rest is handled by the server.
As for the actual server/filtering criteria...
Most important is do not dare to assume that you can guess what a user will want filtered! This will vary wildly from person to person, or even mood to mood.
Setup the server to use a combination of bad words, bad link destinations (.ru and .cn domains, for example) and public spam-filtering services.
The most important thing is to offer users some way to choose and ideally adjust what is applied, for them.

Categories

Resources