How to prevent variable injection in javascript and html5 games - javascript

I have used this html5 Snake game on my website , but problem is that it can be hacked so easily .
http://cssdeck.com/labs/classic-snake-game-with-html5-canvas
Hackers can inject scores and submit their own scores.
Is there anyway to protect score variable inside the script not to be injected by clients ?

Not as long as the game is implemented entirely on the client side. The "solution" is to implement the game rules and storage on the server side, and have the client be mostly UI, but this might be overkill for such a simple browser game.
You could make it harder by obfuscating the code, but that would only stop people who don't actually care.
If the game is deterministic you could keep a log of all game "events" and send that to the server, where the score would be calculated. This would make it more work to fake a score, but it would still be possible to fake, and it would also be a lot of work to build such a system.

Related

Can the code in the server of Node.js be accessed by the client?

I want to develop a game in NodeJS but i'm not sure how much 'easily' hackable it is. For example if i write my game rules in PHP modifing them will need the hacker to actually get access to the server, instead if my rules where in javascript anyone could easily rewrite the rules as they want.
More over if the game would involve people discovering rules as they play how could i prevent those rules to be there for anyone just by looking at the code.
The actual code of your Node.js app will remain unexposed. Ideally, your client (whatever you're doing on the browser side of things, whether this is rendering html elements or using html5 canvas) will only handle I/O and update your server, while your server will take care of all logic.
You can still use javascript client side, but keep in mind that your fear is legitimate concerning client side javascript. This is why it is common practice to separate input/output code (which happens in javascript on the client) from game logic code that happens on the server. So the worst thing someone would be able to do is to send a message to your server saying they are pressing every key at once, and you can filter for things like this.
Developing in nodejs means javascript on server. Javascript code on server which your players will not be able to see unless you open-source your game. This code won't be exposed to your players.

Strategy Game Server Concept

I´m planning to create a WebGL-based, realtime strategy game, where players are able to play together. I´ll use Node.js to create the game server, and websockets for realtime connections.
I´ve broken my mind about what would be the best concept to synchronize the clients.
One possibility would be to send only the orders of the users (moving units, building buildings etc.) to the server, which sends them to all other clients. But here, I have the problem of the delay. I think that the games would get async this way.
Another possibility would be to calulate the game on the server. The clients still send the instructions to the server, but the server sends now all changed states of all units&buildings to the clients in a high interval. The problem is here the high amount of data and how fast this can be...
Do you have some other ideas or improvement proposals?
Thanks!
Basically you have to decide between speed vs security.
Letting the client do the job and the calculations is faster but the data is at risk because the client can manipulate the data.
On the other side, having the server do all the job is slower but the data is more secure.
You could opt for a dual approach, decide to let the client calculate only some data, synchronize and then check for its validity, and let the rest being executed on the server.
It also depends on how fast the game runs, the amount of data to calculate, the speed of the server and band/connections, etc...
You should prototype both methods and try some tests to emulate the client and servers load.
If the game is small I would opt for a more server-side work. On the other hand, for a much complex game probably sharing more work to the client is best. Anyway I think a tradeoff is always needed.
Here are a few links you may find useful
Multiplayer Game Programming Introduction
Real time strategy networking
Multiplayer Programming thread (old but still with many useful links)
Lag Compensation
Prevent Multiplayer Cheating
The first link has helped me a lot back in the days and imho is still one of the best resources avaiable on the subject.
Books
Multiplayer Game Programming
I would suggest to watch these resources regarding browser based game development concepts:
Multiplayer Gaming with HTML5: Are We Ready?
Realtime HTML5 Multiplayer Games with Node.js
HTML5 Games 0.3: Seeing the Future
Unfortunately I have no experiences in WebGL based online games, but usually it is a good approach to let the game logic be executed on the client side, and synchronize the results.
In this approach it is important to keep track of what game object is "owned" by what client. Clients only send updates (creation, update, deleteion) from their own objects and receive the updates of the other game objects from the other clients.
Additionally you can set up a messaging framework to deliver additional messages like "Player has entered/left" or something like that.
This concept has proven useful for a game I created, and I hope it is as useful to you.
You should have the game state and logic on the server, otherwise your game is wide open to cheating. The server is the ultimate authority the game state.
Not sure about WebGL, but to my understanding following approach will be good.
Initialize all objects (which are common across players) on server and run them
On client start, it will request all renderer (related to specific client) for the objects running on server.
client will render the objects on UI for all recieved renderer.
When client make any update on UI, changes will be notified to server, and server will update the object accordingly
When objects common between players are modified by one player, each player (client) will be notified to make UI changes.
This approach will be specific to common objects not UI / client specific objects.
For security reasons, all the logic should be on servers side, and all the data update is on server.
But the client is able to predict some logic and play animation first, which is called client prediction.
The server side is in charge of verify the client logic, if there is no cheating, all done.
If there is someone cheating, the server can tell the client to go back to right state.
If you are using node.js for server, there is an open source framework , pomelo .
And there is also a full source code demo and online demo for it: lordofpomelo

What good ways are there to prevent cheating in JavaScript multiplayer games?

Imagine a space shooter with a scrolling level. What methods are there for preventing a malicious player from modifying the game to their benefit? Things he could do that are hard to limit server-side is auto-aiming, peeking outside the visible area, speed hacking and other things.
What ways are there of preventing this? Assume that the server is any language and that the clients are connected via WebSocket.
Always assume that the code is 100% hackable. Think of ways to prevent a client completely rewritten (for the purposes of cheating) from cheating. These can be things such as methods for writing a secure game protocol, server-side detection, etc.
The server is king. Clients are hackable.
What you want to do is two things with your websocket.
Send game actions to the server and receive game state from the server.
You render the game state. and you send input to the server.
auto aiming - this one is hard to solve. You have to go for realism. If a user hits 10 headshots in 10ms then you kick him. Write a clever cheat detection algorithm.
peeking outside the visibile area - solved by only sending the visible area to each client
speeding hacking - solved by handling input correctly. You receive an event that user a moved forward and you control how fast he goes.
You can NOT solve these problems by minifying code. Code on the client is ONLY there to handle input and display output. ALL logic has to be done on the server.
You simply need to write server side validation . The only thing is that a game input is significantly harder to validate then form input due to complexity. It's the exact same thing you would do to make forms secure.
You need to be really careful with your "input is valid" detection though. You do not want to kick/ban highly skilled players from your game. It's very hard to hit the balance of too lax on bot detection and too strict on bot detection. The whole realm of bot detection is very hard overall. For example Quake had an auto aim detection that kicked legitedly skilled players back in the day.
As for stopping a bots from connecting to your websocket directly set up a seperate HTTP or HTTPS verification channel on your multiplayer game for added security. Use multiple Http/https/ws channels to validate a client as being "official", acting as some form of handshake. This will make connecting to the ws directly harder.
Example:
Think of a simple multiplayer game. A 2D room based racing game. Upto n users go on a flat 2D platformer map and race to get from A to B.
Let's say for arguments sake that you have a foolsafe system where there's a complex authetication going over a HTTPS channel so that users can not access your websocket channel directly and are forced to go through the browser. You might have a chrome extension that deals with the authentication and you force users to use that. This reduces the problem domain.
Your server is going to send all the visual data that the client needs to render the screen. You can not obscure this data away. No matter what you try a silled hacker can take your code and slow it down in the debugger editing it as he goes along until all he's left with is a primitive wrapper around your websocket. He let's you run the entire authentication but there is nothing you can do to stop him from stripping out any JavaScript you write from stopping him doing that. All you can achieve with that is limit the amount of hackers skilled enough of accessing your websocket.
So the hacker now has your websocket in a chrome sandbox. He sees the input. Of course your race course is dynamically and uniquely generated. If you had a set amount of them then the hacker could pre engineer the optimum race route. The data you send to visualise this map can be rendered faster then human interaction with your game and the optimum moves to win your racing game can be calculated and send to your server.
If you were to try and ban players who reacted too fast to your map data and call them bots then the hacker adjusts this and adds a delay. If you try and ban players who play too perfectly then the hacker adjusts this and plays less then perfect using random numbers. If you place traps in your map that only algorithmic bots fall into then they can be avoided by learning about them, through trial and error or a machine learning algorithm. There is nothing you can do to be absolutely secure.
You have only ONE option to absolutely avoid hackers. That is to build your own browser which cannot be hacked. Build the security mechanisms into the browser. Do not allow users to edit javascript at runtime in realtime.
At the server-side, there are 2 options:
1) Full server-side game
Each client sends their "actions" to the server. The server executes them and sends relevant data back. e.g. a ship wants to move north, the server calculates its new position and sends it back. The server also sends a list of visible ships (solving maphacks), etcetera.
2) Full client-side game
Each client still sends their actions to the server. But to reduce workload on the server, the server doesn't execute the actions but forwards them to all other clients. The clients then resolve all actions simultaneously. As a result, each client should end up with an identical game. Periodically, each client sends their absolute data (ship positions, etc.) to the server and the server checks if all client data is identical. Otherwise, the games are out of sync and someone must be hacking.
Disadvantage of the second method is that some hacks remain undetected: A maphack for example. A cheater could inject code so he sees everything, but still only sends the data he should normally be able to see to the server.
--
At the client-side, there is 1 option:
A javascript component that scans the game code to see if anything has been modified (e.g. code modified to render objects that aren't visible but send different validation data to the server).
Obviously, a hacker could easily disable this component. To fix that, you could force the client to periodically reload the component from the server (The server can check if the script file was requested by the user periodically). This introduces a new problem: the hacker simply periodically requests the component via AJAX but prevents it from running. To avoid that: have the component redownload itself, but a slightly modified version of itself.
For example: have the component be located at yoursite/cheatdetect.js?control=5.
The server will generate a slightly modified cheatdetect.js so that in the next iteration, cheatdetect.js?control=22 (for example) must be downloaded. If the control mechanism is sufficiently complicated, the hacker won't be able to predict which control number to request next, and cheatdetect.js must be executed in order to continue the game.
There's nothing you can really do to prevent anyone from modifying your JS or writing a GreaseMonkey script. However you can make it hard for them by minifying your script as well as making your code as cryptic as possible. Maybe even throwing in some fake methods or variables that do nothing but are used to throw an attacker off. But given enough time, none of these methods are completely foolproof, as once your code goes to the client, it is no longer yours.
The only way I can even think of implementing this is by modifying your Javascript to function as a client and then designing a central server mechanism to validate data sent from that client. This is probably a big change to implement and will most likely make your project more complex. However, as was said earlier, if the application runs entirely on the client, the client can pretty much do whatever they want with your script. The only way to secure it to use a trusted machine to handle validation.
They don't have to touch your client-side code -- they could just sniff and implement your Websocket protocol and write a tiny agent that pretends to be a human player.
Update: The problem has a few parts, and I don't have answers off the top of my head, but the various options could be evaluated with these questions in mind:
How far are you willing to go to prevent cheating? If you only care about casual cheating, how many barriers are enough to discourage the casual cheater? The intermediate Javascript programmer? A serious expert? Weighing this against the benefits of cheating, is there anything of real value at stake, like cash and prizes, or just reputation?
How do you get a high confidence that a human is providing inputs to your game? For example, with a good enough computer vision library I could model your game on a separate machine feed inputs to the computer pretending to be the mouse, but this has a high relative cost (not worth my time).
How can you create a chain of trust in your protocol such that knowledge of (2) can be passed to the server, and that your server is relatively confident your client code is sending the messages?
Sure many of the roadblocks you throw up can be side-stepped, but what is the cost to the player and you? See "Attrition warfare".
Some other methods that can be implemented:
Make the target elements difficult for a script to distinguish from other elements. Avoid divs with predictable class and id names if possible. Inject styling using JavaScript instead of using classes. Think like a hacker and make it hard on yourself.
Use decoys that a script will fire on. For instance, if the threat vector is a screen scraping algorithm using pixel colors, throw some common pixel colors in non-target elements. Hits on these non-targets could seem inconsequential to the cheater, but would be detectable. You don't want the cheater to know why you know.
Limit the minimum time between actions to slightly below the best human levels. The best players will hit that plateau, and it won't matter as much who's cheating, and immediately be able to detect anyone scripting faster than that by side-calling method calls.
Random number generators are typically uniform. Human nature is not. Likely a random number generator will have values within a set limit and even distribution. Natural distribution is a Gaussian curve. If you sampled the distribution and it looks like a square wave in the x and y axis, 100% it's a cheater. This will be fairly difficult for the cheater to detect the threshold for the algorithm because it's a derivative of the random, and not the random distribution itself. You're also using aggregate data and not individual plays to detect it, so reverse engineering the algorithm would be extremely difficult without knowing your detection algorithm.
Utilize entropy whenever possible. Avoid predictable game plays. Imagine a racing game on a set collection of race tracks. Each game play could have slightly differing levels of traction, horsepower, and momentum. The script would have to be extremely good to beat it. In a scrolling game, you can alter factors that are instinctual to humans, but difficult for computers, such as wind force, changes in gravity, etc. It would also make it more fun as a side benefit.
Server generated tokens can be used to validate UI elements were used and not calls to the code itself. Validation can be handled in one call at the end of the game comparing events to hashed codes of UI elements. The token should be a hash with a server private key and some value of the UI element.
Decoy the cheater with data they think you're using to detect cheats. Such as calls to a DetectCheat method with dummy calls to a fake backend. It's the old magician's trick. Wave your hand over here, while you slip a card into the deck with the other hand. Let them waste days on end in a maze that has no exit, with lot's of hair pulling.
I'd use a combination of minification and AJAX. If all of the functions and data aren't loaded into the page, it'd be more difficult to cheat.
On the other hand, modding turned out to be a very profitable tool for companies like Id Software. Perhaps allowing the system to be modded might make the game that much more enjoyable to the community at large.
Obfuscate your client exposed code as much as possible. Additionally, use some magic.
You can edit the javascript on the browser and make it work.
Some people suggest that make a call to check with the server. So after making a call to the server, it will be validated in the server. Once validated, it will come to client side and do actions. But I think even this is not foolproof.
For eg.,. for a Basic login action : in angular while making a call to server, the backend validates username & pwd and if validated, it will come back to the client and let the user login using angular.
When I say login using angular, it is going to store things in cookies, like user objects and other things. But still the user can remove the JS code which is making the call to backend, and return TRUE(wherever needed) and insert user object(dummy) to cookies and other objects(whatever needed) and login. It is a very difficult thing to do, but it is doable. In many scenarios, this is not desirable even if it takes hours to edit/hack the code.
This is possible in single page applications, where JS files dont get reloaded for each page. To mitigate the possibility of getting hacked we can use minified codes. And I guess if actions like this is done in backend(like login in Django) it is much safer.
Please correct me if I am wrong.

How safe is "the future of browser gaming"?

HTML5 will be widely adopted as a way to design games, is the prediction. But I have my questions about this: how can an online HTML5 game ever be secure?
Let me give you an example: imagine this platform game where you gain badges when you win, for example, an extremely hard level. When you have actually won this badge, a request is made to the server, in order to update your online profile. Isn't it extremely simple for a hacker to just send this request and gain the badge, without playing the actual game? Because:
The client-side source code is visible and impossible to hide
It is possible to execute Javascript from the command-line
I don't see a way to prevent this hacker from gaining his badge... Is there any way to make this game safe?
Yes, if you designed your game like that, it would be very easy to hack. But why is this specific to HTML5? You could do that with any type of game that was written like that. Even with a native desktop game you could still fake the request. The only difference is that faking HTTP requests is easier than reverse-engineering requests made by a desktop game.
The solution would be to add some kind of "validation" to the victory--the actual algorithm would vary from game to game. Maybe have the server track the game's progress while the user is playing. If it were a game of chess, for example, you could send every move to the server and have the moves validated to make sure they work out correctly. This gets more complicated with real-time games, though.
But whatever algorithm you decide to use, it will be defeated. Even the chess validation that I just mentioned could be bypassed: you could just "create" your own valid game of chess and just send the same moves to the server every time, ensuring that the game was valid. (This is assuming that the player is against a computer--having two humans play against each other would make things easier.)
It's no different from any Flash-based game or indeed a game with a downloadable client like World of Warcraft. Anything integral to the game's fairness has to be handled on the server.
One way that HTML5 can be more secure is that you can change it at any time. So let's say you have an AJAX call to provide a user with a reward. You could periodically change the signature of this call, so that 'cheats' would no longer work. Be sure to keep track of players that are still using the old API, and you can penalize the players using the cheats.
No, this won't solve all of your problems, and there are ways the most savvy players will be able to work around this (depending on how elaborate your changes are), but it does provide some way to deal with this, especially if your game requires significant investment. Players may not be willing to risk their progress if they feel like there is a chance they'll be caught. Just make sure you have a clear code of conduct that details punishments for cheating.

Is Flash/Actionscript any safer than Javascript for persistent online game?

I'm finding lately how unsecure Javascript is when programming a game (I'm trying to do a turn based RPG and currently the battle calculations are done through Javascript which any player can cheat with of course giving themselves as much XP as they want), so I'm wondering if I were to move my battle screen to flash if this would be any more secure, or is there just as easy of a way to cheat this?
Come on. It's the same question really. Answer remains the same too:
No matter what the game, whether JS Flash or native binary, if the scoring system is vulnerable, people will tamper if the game is good enough. Stick to clever serverside every time.
This is not a problem that can be solved by obfuscation at the client end. There's plenty of prior art concerning keeping high-score tables/game data secure. Sharpen your google-fu and have a look.
Although the title of this post would suggest it's not applicable, I'd consider the difference between a browser/non-browser game to be irrelevant in this regard. As such, take a look:
Secure Online Highscore Lists for Non-Web Games
This is very slightly safer as flash source is harder to read then js source. However neither is particularly safe.
As I said in a previous answer, a secure system can not trust client score input. It doesn't matter whether the intended program is Flash or JavaScript. Once you send the program to the client they have any required key. So you can't rely on the client giving you accurate scores. The only reliable way to do it is to move score calculation to the server. Then, for a bot to play it still would have to calculate every movement manually.

Categories