Ideas for designing a Secure, "Low Cost" method for confirming client-side game results - facebook

This is more a system design question/challenge, than a coding question.
Basically, I'm thinking of throwing together a Bejeweled-esque game on Facebook using just HTML, CSS, and javascript. This is mostly out of a desire to learn all the little caveats of FBJS via a non-trivial project.
So here's the deal. When developing for Facebook, actual API calls are very expensive; not only is there an additional POST to the Facebook servers, there's also the api call limit and throttling to worry about. In a nutshell, the fewer calls to Facebook the better. Combine this with the timing concerns of even this simple puzzle game, and there's good reason to aggressively minimize the number of callbacks in general.
Not being a security expert, here's the design I've come up with:
Embed a random seed in the game page.
Use that seed to create the game board (As well as additional pieces as needed).
Tweak the seed (xor, concatenate and hash, something like that) after each player move, based on time since last move. Edit: I should probably also include the actual move taken in mutating the seed.
Upon game completion post back the following: game start time, each move taken and when, and the client side results.
On the server, re-run the game with the given data, sanity checking the start time and move times, and then confirm that the results match.
To mitigate denial of service, the game itself will be tweaked to have a win by turn X condition.
To discourage the server being used as a "oracle" of sorts, a user posting back an invalid game will be banned for some constant time X (X being on the order of minutes).
This design requires three Facebook call per game played: one to store the random seed before the game is played, one to fetch it after the game is finished, and one to update the player's score if the game is valid.
What I'm trying to proof the system against is straight up score spoofing (http://...?myscore=999999999, or similar). I'd also like to mitigate "look ahead" attacks, wherein the user can tell what pieces are coming to the board next. Denial of service attacks on the hosting server (intentional or otherwise) should also be prevented.
The actual question, can anyone see a flaw in this design? Equivalently, is there a simpler design that meets my criteria?
Note: I am aware how unnecessary this probably is, but its an interesting question none the less.
I'm going to try and throw some numbers up here to futher illustrate my reasoning, these are pretty rough but I hope helpful.
Assuming a 10x10 game board, there are ~200 potential moves (swapping two adjacent pieces) most of which are invalid. Let's say there are on average 5 valid moves per "turn". If we constrain player actions to the frame of 50 to 30,000 milliseconds, there are 149,750 potential new hashes provided the "tweaking" algorithm doesn't discard bits; I feel confident in say there are at least 10,000 potential new hashes which must be calculated by an attacker assuming a cryptographically secure hash is used. If you throw a min-max algorithm at this, your decision tree explodes very quickly. Throw a game session expiration at this, say 30 minutes, and I believe the attack because equivalent in complexity to writing a little bot program to play for you which cannot reasonably be defended against.

If the client code calculates the next piece and you can't hide this algorithm very well, then some bored college student will figure this out. As a result, they will be able to generate a massive score and defeat your intentions.

I tend to say that it is impossible to do. Why? You cannot trust the client - I could just analyse and completly rewrite the client side code and return whatever values I like. The only way to protect you from cheating and all kinds of attacks is to perform the logic at the server - the client will just collect user input and display the server output. But this is completly against your design goal to minimize the number of server calls.

Related

What use cases are there for Early Media with IVRs?

I would say that the following are valid use cases for Early Media when used for IVRs:
Filtering
Disconnect incoming calls based on certain criteria (such as callers from a specific area code, or to play a message before hanging up on after hour callers).
Rate limiting
For example to limit the number of simultaneous callers, where the excess calls are either disconnected, or placed in a queue. (I'm not sure if the queue example is possible though without answering the call.)
Are there more?
Some links that were helpful:
https://www.dialogic.com/webhelp/csp1010/8.4.1_ipn3/sip_software_chap_-_early_media.htm
https://wiki.asterisk.org/wiki/display/AST/Early+Media+and+the+Progress+Application
https://freeswitch.org/confluence/display/FREESWITCH/Early+Media
3) Legal: in some countries it is illegal for a call center using payed line (caller pay per minute) to accept a call without sending it straight to an agent. So you can't accept the call, give the user some waiting music for 15 minutes (and make them pay for the privilege of waiting as well).
Result: you don't accept the call. However, this creates a new problem: if the caller only hears the ring back tone for those 15 minutes, he/she will assume no one will answer and hangs up.
Using early media, you can give them the traditional "your call is very important to us, please hold on"-type of experience without accepting the call and without starting to charge money. Of course this also depends somewhat on how much the provider is willing to tolerate, as this can also affects their income (depending on their own business model).
4) Comfort: you may not be aware of this, but the sound you hear as caller when the other side is ringing (ring-back tone), is not universally the same throughout the world. A company with a global number may wish to use early media to provide a ring-back tone more familiar to you, depending on where you are calling from. It was always a bit niche of a concept but some target audiences are statistically more likely to hangup if they hear an unfamiliar sound. 15-20 year ago this might have been a concern to some, but in the era of smartphones and internet calls, I doubt anyone really worries about it anymore.

How to synchronize a 1v1 realtime action online mini game?

What I'm trying to make
Hi, game development newbie here. The game I am trying to make is fairly simple. It's almost exactly like the old FC game "Ballon Fight" except that I'm trying to make it online where players can go through a match making to find opponents.
BalloonFight:
What I Read
I have read some articles, and found most of them lead to two approaches:
Put all game logic on the client, and the client sends player inputs to server on every frame update. The server acts like a dispatcher which only makes sure player A's input is received by both client A and B. My understanding is that if we see the client in this case as a pure function, and if the two players' inputs are received by each other, the game should produce same results on both clients. Thus synchronization is achieved.
Put all game logic on the server, and let the server do the calculations and send back results to both clients. In this case, clients only worry about displaying.
My Fears
Solution 1 sounded like a simpler one to me, but immediately I realized when network problem is put into account, it becomes incredibly complicated. Losing player A's connection for a few seconds means all the input is lost in that period. What I can guess is, to counter that, the server has to detect whether player A is lagged out and accumulate input from player B until player A is back then feed all the accumulated input to player A's client. Player A's client then need to do a fast forward to catch up. This sounds like there's huge amount of infra work on both client side and server side.
Solution 2 on the other hand looks very daunting to me, since for now I have only written some games on the client side.
My questions
in order to make a simple online game like this, what is the most beginner friendly way to synchronize game state?
if I were to use solution 1 stated above, is there any framework that provides such infra so that I don't have to handle network issues all by myself?
In advance, thank you game dev gurus.

How to prevent so file hacking in so file

In my app(unity5, il2cpp build), There is a function like
"GetScore()"
Unfortunately, i found the hacked version of my app in the black market. that hacked version's "GetScore()" function always returns 100. The original return value has to be under 10.
I guess this hacked App is repackaged by using like 'il2cppDumper' and changing my return value to 100;
Is there any way to prevent this problem?
Security is always a matter of making it harder for hackers - you can never make it impossible for them to tamper.
So here are some thoughts:
Obfuscation: GetScore() gets BananaJungle() - hackers cannot find the correct function without stepping through the source code for hours (hopefully)
Validate the score on multiple spots: the function calling GetScore() should do a sanity check: "is it below 10?"
In Addition to this: You may want to ignore scores above 10 to fool the hacker he succeeded. You may lock the app after 2 hours or so.
Add a ScoreLogger somewhere that logs the history of the score, so getScore() may return values <10 but someone might just overwrite the score in code to 999999. ScoreLogger will check the score history for jumps etc.
Validate Score with total playtime (approximately)
You won't ever keep hackers from hacking your games, even if it does indeed have a backing server. Just look at all the unofficial world of warcraft servers. You can keep things relatively safe if you have a server, you keep its source code secure, and your game is meaningless without its server (think Dota 2 with no multiplayer capabilities...). Even then, you can't actually validate the player's every move, unless it's a turn based game and you actually send every move the server to be processed (this works in Hearthstone, for example, but not in WoW, hence all the anti-cheating tools). EA couldn't do it, Rockstar couldn't do it, Activision couldn't do it, even the mighty Denuvo couldn't do it, you certainly can't do it.
However, you should stop and ask yourself why you want your game to be that secure. Out of every 1000 cheaters you stop, maybe one or two would actually pay. You should put in a moderate amount of effort on security (take KYL3R's advice), simply to keep honest people honest. Dishonest people will always find a way, so don't worry about them so much that you end up wasting time on (useless) security; time you could spend on making your game better.
Oh and by the way, that's also one way to keep hackers out: frequent updates to the game. They have no life, but they don't have enough time to keep making a hacked version of every game on the market every week.

Where to draw the line with reactive programming [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 6 years ago.
Improve this question
I have been using RxJava in my project for about a year now.
With time, I grew to love it very much - now I'm thinking maybe too much...
Most methods I write now have some form of Rx in it, which is great! (until it's not).
I now notice that some methods require a lot of work to combine the different observable producing methods.
I get the feeling that although I understand what I write now, the next programmer will have a really hard time understanding my code.
Before I get to the bottom line let me give an example straight from my code in Kotlin (Don't dive too deep into it):
private fun <T : Entity> getCachedEntities(
getManyFunc: () -> Observable<Timestamped<List<T>>>,
getFromNetwork: () -> Observable<ListResult<T>>,
getFunc: (String) -> Observable<Timestamped<T>>,
insertFunc: (T) -> Unit,
updateFunc: (T) -> Unit,
deleteFunc: (String) -> Unit)
= concat(
getManyFunc().filter { isNew(it.timestampMillis) }
.map { ListResult(it.value, "") },
getFromNetwork().doOnNext {
syncWithStorage(it.entities, getFunc, insertFunc, updateFunc, deleteFunc)
}).first()
.onErrorResumeNext { e -> // If a network error occurred, return the cached data and the error
concat(getManyFunc().map { ListResult(it.value, "") }, error(e))
}
Briefly what this does is:
Retrieve some timestamped data from storage
If data is not new, fetch data from network
Sync network data again with the storage (to update it)
If a network error occured, again retrieve the older data and the error
And here comes my actual question:
Reactive programming offers some really powerful concepts. But as we know with great power comes great responsibility.
Where do we draw the line? Is it OK to fill our entire programs with awesome reactive oneliners or should we save it only for really mundane operations?
Obviously this is very subjective, but I hope someone with more experience can share his knowledge and pitfalls.
Let me phrase it better
How do I design my code to be reactive yet easy to read?
When you pick up Rx, it becomes this awesome shiny hammer and everything starts looking like a rusty nail just waiting for you to bang in.
Personally, I think the biggest clue is in the name, reactive framework. Given a requirement, you need to reflect upon whether a reactive solution truly makes sense.
In any Rx proposition, you are looking to introduce one or more event streams and carry out some action in response to an event.
I think there are two key questions to ask:
Are you in control of the event stream?
To what degree must you complete responses at the rate of the event stream?
If you do not have control of the event stream and you must respond at the rate of the event stream then Rx is a good candidate.
In any other circumstance, it is probably a poor choice.
I have seen many examples where people have jumped through hoops to create the illusion of a lack of control in order to justify Rx - which seems crazy to me. Why give up the control that you have?
Some examples:
You have to extract data from a fixed list of files and store it in a database. You decide to push each file name into a subject and create a reactive pipeline that opens each file and projects the data, then processes the data in some way and finally writes it to the database.
This fails the control test and the rate test. It would be far easier to iterate over the files and pull them in and process them as fast as you can. The phrase "decide to push" is the giveaway here.
You need to display stock prices from a stock exchange.
Clearly this is a good choice for Rx. If you can't keep up with the rate of prices in general, you are screwed. It might be the case that you conflate prices (perhaps to provide an update only once every second) - but this still qualifies as keeping up. The one thing you can't do is ask the stock exchange to slow down.
These (real world) examples pretty much fall at opposite ends of the spectrum and don't have much grey area. But there is a lot of grey area out there where control isn't clear.
Sometimes you are wearing the client hat in a client/server system and it can be easy to fall into the trap of sacrificing control, or putting control in the wrong place - which can easily be fixed with correct design. Consider this:
A client application displays news updates from a server.
News updates are submitted to the server at any time and are created in high volume.
The client should be refreshed at an interval set by the client.
Refresh interval can be changed at any time and the user can always request an immediate refresh.
The client only shows updates tagged with particular keywords, as specified by the user.
The news updates are sometimes lengthy and the client should not store the full content of news updates, but rather display the headline and summary.
At user request, the full content of an article can be shown.
Here, the frequency of news updates is not in control of the client. But the desired refresh rate and the tags of interest are.
For the client to receive all the news updates as they arrive and filter them client side isn't going to work. But there are plenty of options:
Should the server send a data stream of updates taking into account the client refresh rate? What if the client goes offline?
What if there are thousands of clients? What if the client wants an immediate refresh?
There are lots of valid ways to tackle this problem that include more or less reactive elements. But any good solution should take account of the client's control of tags and desired refresh rate, and the lack of control of news update frequency (by client or server). You might want the server to react to changes in client interest by updating the events that it pushes to the client - which it pushes only as long as the client is listening (detected via a heartbeat). When the user wants a full article, then the client would pull the article down.
There is much debate in the Rx community about back-pressure. This is the idea that the client should inform the server when it is overloaded and the server respond by somehow reducing the event stream. I think this is a misguided approach that can lead to confusing designs.
To my mind, as soon as a client needs to give this feedback, it has failed the response rate test. At this point, you are not in a reactive situation, you are in an async enumerable situation. i.e. The client should be saying "I am ready" when it is ready for more and then waiting in a non-blocking fashion for server to respond.
This would be appropriate if the first scenario were modified to be files arriving in a drop-folder, of varying lengths and complexity to process. The client should make a non-blocking call for the next file, process it, and repeat. (Add parallelism as required) - and not be responding to a stream of file-arrived events.
Wrap up
I've deliberately avoided other valid concerns such as maintainability of code, performance of Rx itself etc. Most because they are addressed elsewhere and more importantly because I think the ideas here are more divisive than those concerns.
So if you reflect on the elements of control and response rate in your scenario you and will probably stay on the right track.
The response rate issue can be subtle - and the degree aspect is important. Arrival rate can fluctuate, and there is going to be some acceptable degree of fluctuation in response rate - clearly, if you don't ultimately have a way to "catch up" then at some point the client will blow up.
I find that there are two things I keep in mind when writing Rx (or any mildly sophisticated/new technology)
Can I test it?
Can I easily hire someone that can maintain it. Not struggle to maintain it, but will be fine left alone to maintain it?
To this end, I also find that just because you can, doesn't always mean you should. As a guide I try to avoid creating queries that are over say 7 lines of code. Queries bigger than this, I try to separate into sub queries that I compose.
If code you have provided is at the core of the code base, and is at the extreme end of the complexity, then It may be fine. However, if you find all of your Rx code carries that much complexity, you may be creating a difficult to work with code base.

High latency in an iPhone mmorpg

Right now I'm trying to make a mmorpg for the iPhone. I have it set up so that the iPhone requests for the player positions several times a second. How it does this is that the client sends a request using asynchronous NSURLConnection to a php page that loads the positions from a mysql database and returns it in json. However, it takes about .5 seconds from when the positions are requested to when they actually get loaded. This seems really high, are there any obvious things that could cause this?
Also, this causes the player movement on the client to be really choppy too. Are there any algorithms or ways to reduce the choppiness of the player movement?
Start measuring how long the database query takes when you run it outside your iPhone.
Then measure how long it takes when you send the same http request from something other than your iPhone(It's e.g. a 10-15 line c# program to figure this out).
If none of the above show any sort of significant latency, the improvements need to be done on the iPhone side. Some things to look out for:
GPRS/3G has rather high latency
GPRS/3G has rather high bit error rates - meaning there's going to be quite a few dropped packets now and then which will cause tcp to retransmit and you'll experience even higher latency
HTTP has a lot of overhead.
JSON adds a lot of overhead.
Maybe you'll need to come up with a compact binary format for your messages, and drop HTTP in favor of a custom protocol - maybe even revert to UDP
The above points generally don't apply, but they do if you need to provide a smooth experience over high latency,low bandwidt, flaky connections.
At the very least, make sure you're not setting up a new TCP connection for every request. You need to use http keep-alive.
I don't have any specific info on player movement algorithms, but what is often used is some sort of movement prediction.
You know the direction the player is moving, you can derive the speed if it's not always constant - this means you can interpolate over time and guess his new position, adjust the on screen position while you're querying for the actual position, and adjust back to the actual position when you get the query response.
The trick is to always interpolate over time within certain boundaries. If your prediction was a bit off compared to what the query returned, don't immediatly snap the positon back to the real position. Do interpolation between the current position and the desired postion over a handful of frames.
On the server side you should be using some system that keep running and that keeps the database connection open all the time. Preferably it would also cache things instead of requesting them from database all the time.
Also, do not make a new HTTP request for every update. It would be best if you hadn't need to use HTTP at all, as it really isn't suitable for realtime comminunication.
GPRS typically has 600 ms ping time, 3G has 300 ms and HSPA has 100 ms. See which mode is being used. Notice that some devices (I don't know of iPhone) drop from HSPA to regular 3G for power-saving reasons whenever there is not enough traffic to justify the faster mode.
As for position, a rather common practice is to apply a linear prediction, i.e. make the character continue movement in current direction, at the current speed, even when no data from server is available yet.
Most importantly: benchmark/profile to see where the latencies are. Is it your server, the network connection or the application.
Loading the player positions that fast has downsides.
It hammers your server.
3G isn't really meant to support low-latency applications
So I don't see a mmorpg working without some necessary shortcuts at this time, e.g. extrapolating paths based on their velocity and position. Loading positions will not work as fast as you want, especially with a server based on PHP of all things.
Either way, when developing for a mobile platform you're going to have to make sacrifices in terms of features versus a fully-featured desktop implementation.
I might also reimplement some of the more critical stuff if not the whole server in a faster language, e.g. C++.