views:

698

answers:

16

I am designing a web site in which users solve puzzles as quickly as they can. JavaScript is used to time each puzzle, and the number of milliseconds is sent to the server via AJAX when the puzzle is completed. How can I ensure that the time received by the server was not forged by the user?

I don't think a session-based authenticity token (the kind used for forms in Rails) is sufficient because I need to authenticate the source of a value, not just the legitimacy of the request.

Is there a way to cryptographically sign the request? I can't think of anything that couldn't be duplicated by a hacker. Is any JavaScript, by its exposed, client-side nature, subject to tampering? Am I going to have to use something that gets compiled, like Flash? (Yikes.) Or is there some way to hide a secret key? Or something else I haven't thought of?

Update: To clarify, I don't want to penalize people with slow network connections (and network speed should be considered inconsistent), so the timing needs to be 100% client-side (the timer starts only when we know the user can see the puzzle). Also, there is money involved so no amount of "trusting the user" is acceptable.

+1  A: 

excuse me but why you can't use the time on the server? the time when you recieve the response will be the one which you use to calculate the score.

makevoid
Network transmission is not instantaneous. Mileage varies *greatly*.
Josh Stodola
+3  A: 

Depending on the server side implementation you have, you could put the timing functionality on the server side. Record the time that the webpage request was made (you could put that into a database if you liked) and then when the answer is received get the current time and perform some arithmetic to get the duration of the answer. You could store the time in the session object if you liked instead of the database as well although I don't know too much about its integrity in there.

Ambrosia
+11  A: 

You can't guarantee the security of the timings cryptographically, because the client's browser can't do secure computation. Any means for encrypting to/from the server could be bypassed by adjusting the actual timings.

And timing on the server doesn't work, either - if you don't take account of latency in the round-trip-time, users with lower latency connections will have an advantage; if you do, users could thwart the compensation phase by adding extra latency there and then removing it later.

You can, of course make it difficult for the users to modify this, but security by obscurity is an unsustainable policy anyway.

So it comes down to either trusting your users somewhat (a reasonable assumption, most of the time) and designing the game so it's not trivial to circumvent the timings.

Peter
I cannot trust the users because there is money involved (prizes for quickest times) and, generally speaking, this sounds like a bad policy. Not only are some people not trustworthy, accounts of law-abiding users (with weak passwords) can be hijacked and used maliciously.
Alex Reisner
unfortunately you're stuck then. your best bet is to go with server-based timing only, with no allowance for latency. that's the only secure way (but it's not very good, of course).
Peter
Lower latency will give you an advantage of, 0.5 seconds tops. Either these are *very* easy games, or it will matter little.
Agos
+3  A: 

You have to use server-side time here. Here is how I would do it:

Make an AJAX request on document ready to ping the server. When server-side code receives the ping, store the server-side time as a session variable (making sure the variable does not already exist). When they finish the quiz, take the server-side time again and compare it with the session variable to determine their duration. Remove the session variable.

Why this works:

  • You do not start the timer before they see the quiz
  • The network delay is factored in, because the timer does not start until the AJAX request comes in (if they have a slow connection, the AJAX request will be slow)
  • Ping is not spoofable because you make sure the session variable does not exist before storing

EDIT: I wanted to add that you could continue to keep client-side time, and include it in the final post. Then you can compare it with your server-side calculated time. If they are reasonably close, then you can trust the client time.

Josh Stodola
this assumes that timing will be consistent - which it won't always be, particularly if the connection is slow.
Peter
@Peter Very true. Wireless connections will vary the most.
Josh Stodola
You could easily block the initial AJAX call, and make it happen just before you finish the puzzle.
rFactor
A: 

The way I would do this is that when the server sends the puzzle to the client, the current time is stored in a session. This ensures that the timing starts immediately after the puzzle has been sent. After the puzzle has been completed, and is sent to the server to check if the puzzle was done right, the server again checks the time and does a comparison.

Obviously slow Internet connections can make this time bigger, but there's nothing you can do about it.

rFactor
You can do something about it; see my answer.
vy32
+3  A: 

It is impossible to start and stop the timer at the client-side without fear of manipulation...

Anything you perform at the client can be altered / stopped / bypassed..

encrypting/decrypting at the client is also not safe since they can alter the info before the encryption occurs..

Since it involves money, the users can not be trusted..

The timing has to start at the server, and it has to stop at the server..

Use ajax to start the timer at the server only if the puzzle contents return with the result of the ajax call. do not load the puzzle and then sent an ajax request as this could be hijacked and delayed while they review the puzzle...

..

Gaby
+1  A: 

As several others have pointed out:

  1. You must use server time, because client time is vulnerable to manipulation.
  2. Checking the time on the server will potentially penalize people with slow network connections, or people that are far away.

The answer to the problem is to use a time synchronization protocol between the client and the server similar to the protocol that NTP uses. Working together, the client and the server determine the amount of delay caused by network latency. This is then factored into the times given to each user.

NTP's algorithms are complicated and have been developed over years. But a simple approach is below; I think that the protocol should work, but you may wish to test it.

Have the client measure the round-trip time with two successive HTTP XMLRPC pings. Each ping returns a different nonce. The second ping requires the nonce from the first ping, which assures that they are sequential. The puzzle time starts when the second HTTP ping is sent from the client. The server timestamps each request and assumes that the puzzle is displayed 1/2 way between the receipt of the first and the second request.

When the puzzle is finished the client pings twice again, following the same protocol as before. The server knows when it receives each request and it knows the time delta. Now take half the time delta and subtract that from when the first ping of the second set is received. That can be safely assumed to be the time that the puzzle was completed.

vy32
Very interesting solution, but I don't fully understand it. (1) If puzzle time starts when the second ping is sent from the client, then doesn't the puzzle itself need to be sent by the server in response to the first ping? Otherwise the client could peek before initiating the sync. (2) Similarly, I assume the client's answer is sent along with the first of the second set of pings? (3) Lastly, can't the client delay the final ping to exaggerate latency? Am I missing something?
Alex Reisner
Ah. Those are really good points. I guess the puzzle needs to be sent in response to the second ping, and we can dispense with the second set and just send a response. But you are correct that the client could delay the time between the two pings to create a false sense of long latency. Hm...
vy32
A: 

there is a very fast implementation of cryptography in js here

http://crypto.stanford.edu/sjcl/

it allows public / private key encryption all on the client and I think you can adapt it to encrypt the Ajax communication between your server and the client browser

here is a detailed explanation, which you can adapt to your needs http://crypto.stanford.edu/sjcl/#usage

pǝlɐɥʞ
+2  A: 

You asked a bunch of questions in your original question, I'm only going to answer one of them:

Am I going to have to use something that gets compiled, like Flash? (Yikes.)

Yes. Given your criteria: 1) 100% accurate, and 2) No possibility of user interference, you have to use a compiled binary.

Doesn't have to be flash though - I'd suggest a java applet if the thought of Flash makes you say "Yikes".

Graza
Using a compiled binary doesn't guarantee the user isn't interfering with time measurement. I don't know of a way to measure time in an app that can't be tricked (either by changing the system clock or suspending threads, depending how you do it).
ZoFreX
Somebody could just operate at a lower level, and make direct HTTP calls identical to the ones the compiled binary would make, and the server wouldn't be able to tell the difference.
Anurag
@Anurag - actually, that's point of the compiled binary; you'd sign it cryptographically to deter tampering, even if sent over HTTP
K Prime
@K Prime, It was too late to modify my comment. I was going to prefix "In theory,". And sure it makes it much more tougher, but it's not the binary that has to be cracked necessarily but rather the messages that go on between the client and the server.
Anurag
A: 

I joined Stack Overflow to ask for advice about an idea I had to sort of add a signature to a so that it couldn't be resubmit etc. I was looking for criticism, but no one's answering.

Perhaps posting it here, the idea can be of use to you and I can rope in some answers :D

I won't post it again, but if you want to take a look
http://stackoverflow.com/questions/2067821/idea-to-hinder-xsrf-and-form-spoofing

The short version is that the server generates a token which is only valid for a short time; in the HTML there is a <script> element which provides this token as a GET parameter to the server. The presence of the GET parameter results in the downloaded script checking for GUIDs in the document to confirm it corresponds to the original document. If they are present, it defines an onsubmit event handler to inject a new hidden <input> in the form which includes a new token. It then removes the <script> element (itself) from the document.

When the server receives a form submission, it double checks that the token-parameter is present, and that it corresponds to the URL an METHOD of the original form. If it doesn't the request is treated as suspect.

I'm not saying it will work; just that I've been musing on it.

LeguRi
This sounds similar to the session-based authenticity token I mentioned in my question. You might want to look into what Rails does, which is a pretty thoroughly tested solution. It doesn't work for my situation, however, as I need to check authenticity of a submitted value, not a form.
Alex Reisner
You could still apply the idea to an XMLHttp Request methinks... the heart of it though is to perceive the downloading of an external <script> as part of a kind of three-way handshake.Thanks for the tip; I'll look into hos Rails does it.
LeguRi
A: 

Just a quick thought: why don't you use an iFrame to include the game and it's javascripts and let them reside on the server you have your server side implementation running. Any ajax request should then be sent by the same IP as your server side IP is which would solve the problem of identifying the source. Of course you have to take further measures but already gained a lot of confidence in your "client" side requests. Remember the windowsLive services login and many more like it are based on javascript and the usage of iFrames and are considered secure enough.

ruedi
+6  A: 

This approach obviously makes assumptions and is not invincible. All calculations are done on the client, and the server does some background checks to find out if the request could have been forged. Like any other client-based approach, this is not deterministic but makes it very hard for a lying client.

The main assumption is that long-lived HTTP connections are much faster for transmitting data, even negligible in some cases depending on the application context. It is used in most online trading systems as stock prices can change multiple times within a second, and this is the fastest way to transmit current price to users. You can read up more about HTTP Streaming or Comet here.

Start by creating a full-duplex ajax connection between the client and server. The server has a dedicated line to talk to the client, and the client can obviously talk to the server. The server sends the puzzle, and other messages to the client on this dedicated line. The client is supposed to confirm the receipt of each message to the server along with its local timestamp.

On the server generate random tokens (could be just distinct integers) after the puzzle has been sent, record the time when each token was generated, and pass it over to the client. The client sees the message, and is supposed to immediately relay this token back along with it's local time of receipt. To make it unpredictable for the client, generate these server tokens at random intervals, say between 1 and n ms.

There would be three types of messages that the client sends to the server:

PUZZLE_RECEIVED
TOKEN_RECEIVED
PUZZLE_COMPLETED

And two types of messages that the server sends to the client:

PUZZLE_SENT
TOKEN_SENT

There could be a lot of time variation in the messages send from the client to the server, but much lesser in the other direction (and that's a very fair assumption, hey - we have to start somewhere).

Now when the server receives a receipt to a message it sent, record the client time contained in that message. Since the token was also relayed back in this message, we can match it with the corresponding token on the server. At the end of the puzzle, the client sends a PUZZLE_COMPLETED message with local time to the server. The time to complete the puzzle would be:

PUZZLE_COMPLETED.time - PUZZLE_RECEIVED.time

Then double check by calculating the time difference in each message's sent vs received times.

PUZZLE_RECEIVED.time - PUZZLE_SENT.time
TOKEN_RECEIVED.time - TOKEN_SENT.time

A high variance in these times implies that the response could have been forged. Besides simple variance, there is lots of statistical analysis you can do on this data to look for odd patterns.

Anurag
Correct me if I'm wrong but couldn't the client just always delay the token received and the puzzle received messages by the same amount (or the same percentage) and make it look like the puzzle was completed in less time than it was?
ZoFreX
It sure can. Like I said this solution isn't invincible. Using server push cuts down on the false latency a client can liberally introduce. And that they have to be fairly consistent with it's magnitude. And for any truly client side solution, latency cannot be completely ignored. It just doesn't work if you have clients ranging from an Edge connection on a crappy mobile device, vs somebody with a $25K machine on a T3.
Anurag
I agree that it cannot be ignored. But in the context of a competition with a monetary prize, I would walk the side of the line that disadvantages a few users, rather than letting one canny cheater win the money.
ZoFreX
How many users would be at a disadvantage is subject to many factors. If the total number of players is in the order of millions, there'd be many players whose timings will be very close, and a few milliseconds lost in transit time may hugely impact the end result. Arguably there would be a lot fewer players who'd try to game the system. Why put the majority at a disadvantage because of a few?
Anurag
Because it only takes *one* single dishonest and clever user to put 99.9% of users at an impossible-to-overcome disadvantage when they cheat. Giving even 50% of users a slightly harsh handicap has got to be better than that.
ZoFreX
+7  A: 

Even a compiled application could be forged. If the user changes their system clock halfway through timing, your application will report an incorrect time to the server. The only way to get an accurate upper-bound on the time it takes them is to start timing on the server when the puzzle is given to them, and to stop timing when they supply the answer.

As others have pointed out you can minimise the effect that slow connections have by making the load of the puzzle as small as possible. Load the entire page and "game engine" first, and then use an asynchronous request to load the puzzle itself (which should be a small amount of data) to level the playing field as much as possible.

Unfortunately you can't do latency compensation as this would be open to tampering. However, on a connection that's not being used for anything else, the latency for a request like this would be greatly overshadowed by the time it takes a human to solve a puzzle, I don't think it will be a big deal.

(Reasoning: 200ms is considered very bad lag, and that's the average human reaction time. The shortest possible "puzzle" for a human to complete would be a visual reaction speed test, in which case bad lag would have a 100% markup on their results. So as a timing solution this is 2-OPT. Any puzzle more complex will be impacted less by lag.)

I would also put a banner on the page saying to not use the internet connection for anything else while playing for the best possible speeds, possibly linking to a speed / latency tester.

ZoFreX
+1 for being the first one to actually go into the specifics of actual times involved. It's a very important factor IMO which hasn't been touched in any of the other discussions.
Anurag
I agree with Anurag, but disagree with your numbers. 200 ms is very bad lag *for gamers located in the same country*, but is in fact low by international connection standards, and 500 ms is quite likely with a bad connection in a different country.
Peter
Maybe I'm just spoiled then, but I'm currently connected wirelessly to a very unreliable ADSL connection, and my ping from Manchester in the UK to Chicago in the USA is 182 ms.
ZoFreX
+2  A: 

-- Edit:

This solution is somewhat flawed, as pointed out by ZoFrex below.

-- Old:

Here is a way (but you'll need to do some profiling).

Send down a series of "problems" for the JavaScript to solve, while they are playing the puzzle. Previously, I've sufficiently-sized number N such that it is the result of: prime1 * prime2. This forces the client to factor the number (you can get code to do this in JavaScript) and this will take time (this is where profiling clients comes in, and sending down appropriately-sized primes [obviously, this opens you to degradation-attacks, but nevertheless]).

Then, you just send down say, 500, of these prime-problems (or another type), and let the JavaScript solve them in the background. It will generate a list of solutions, and when you send the completed value, you also send this list. From the total count of answers supplied, you can determine how long they spent on the puzzle.

Cons:

  • Requires profiling to determine capabilities of various clients (and hence difficulty of problems)
  • Can be downgrade-attacked
  • Slightly complicated
  • JavaScript computation may interrupt general puzzle-solving
  • Possible to write a bot to get solve problems faster than JS

Pros:

  • Calculations must be done in order to submit the form
  • If implemented correctly, will prevent all but non-trivial attacks

Clearly, it's attackable, (all proposed answers are), but I think it's reasonable. At least, it would be fun to work on :)

In the end, though, you need to actually install a client-side system with a bit more security. And do note that Flash certainly is not this; it's trivial to decompile. Infact, there was an IQ test here in Australia once, and it was controlled via a Flash app that was done LIVE on television. Of course, the winner was a computer programmer, I wonder why :P

-- Edit:

OP, Also, I linked it in a comment to this post, but just incase you miss it, you are kind of interested in the Hashcash, which is the aim to show that a client has completed some amount of 'Work'. Even if my implementation isn't suitable, you may find a review of that field fruitful.

Noon Silk
thats an innovative solution. i'm using a similar approach but just asking the client to get back to the server more frequently instead of having it solve local puzzles.
Anurag
Anurag: It's actually just a modified "Hashcash" system (http://en.wikipedia.org/wiki/Hashcash). I implemented back when I had a blog, as a non-intrusive CAPTCHA system. (When the user hits 'post' it begins factorisation of a single problem, and it gives the submitted time to the review their post :P)
Noon Silk
This is a very interesting solution. I want to implement this just because it seems like a lot of fun to think about. I didn't know about Hashcash--thanks.
Alex Reisner
Surely the client can just solve say, only one of the problems, and make it look like it took no time at all?
ZoFreX
ZoFrex: Hmm. Damnit. What a fool I am. This needs more thought.
Noon Silk
A: 

I do not think there is a perfect solution. Here is an alternative that makes it harder for cheater but at the same time an unlucky honest solver may lose out.

Get many samples of roundtrip time measurements from each specific devices/location/other combination apriori for each user based on their other interaction with your site. You will also have these measurements for the entire population. You could also be very subtle get the timestamps for when a particular DNS lookup happened from their ISP's resolver (random hostname and you host the authoritative DNS server for that domain).

Once you have this, perform all measurements on the server side (puzzle returned to user, solution received) and subtract out the network time based on previous observations.

Note that even in other solutions you have server load, client load (slow processor, etc.), etc that affect timing.

Make sure you have XSRF protection on puzzle submission page :)

mar
+2  A: 

It's a tricky problem because it's fundamentally unsolvable, so you need to work around the tradeoffs to do your best. There've been several good points made on the technical side including: (a) don't waste your time thinking compiling to Flash, Windows, Silverlight, JVM, or anything will actually help, (b) first transmit the encrypted real puzzle payload, then as the actual bottleneck transmit the key alone, (c) the latency even on 56k of sending a couple hundred bytes is negligible compared to human reaction time.

One thing I haven't seen mentioned is this:

Use after-the-fact auditing and tracking of users. This is how real casinos work. This is, I am told, a big part of how PayPal made their money. In both cases, rather than doing a lot of before-the-fact security, they keep very close tabs on everything about their players, use a lot of technology (statistics, pattern detection, etc) to flag suspicious players and they investigate. In both casinos and PayPal, you can't get your money right away. You have to cash in your chips or wait for the money to make it out of the PayPal system into your real bank. Your system should work the same way-- they can't actually get the money for at least a few days at minimum (longer if you are unable to set up a sufficiently speedy auditing system), giving you time to potentially impound their winnings. You have a lawyer, right? Also, casinos and PayPal know your real life identity (a must for dealing in money) so they can go after you legally-- or more importantly, deter would-be attackers since they could go after them legally.

Combined with the other tips, this may be sufficient to eliminate cheating entirely.

If you find it is not, make your goal not to totally eliminate cheating but to keep it to an acceptable level. Kind of like having 99.99% uptime. Yes, as one poster said, if even one person can compromise it everyone is screwed, but with a good auditing system the attacker won't be able to consistently cheat. If they can cheat 1 in 1000 times if they're lucky and they find they can't cheat more than once or twice before being caught, it won't be a problem since very few will cheat and any given honest user will have an extremely low chance of being affected by an extremely small amount of cheating. It'll be imperceptible. If you ever have a real cheating occurence that hurts an honest user, go out of your way to make the honest user feel satisfied with the outcome to a degree out of proportion to the value of that single customer. That way everyone will be confident in your security. They know they don't have to worry about anything.

People problems are not always solvable with technology solutions alone. You sometimes need to use people solutions. (The technology can help those people solutions work a lot better though.)

Domingo Galdos