Friday, May 24, 2013

DAoC Random function

As I mentioned before, the generation of the RC4 key in this game can easily be instrumented to generate the secret we want.

The pseudo code to generate the RC4 key looks something like this:

repeat 0x40 times
  use rdtsc to generate 1 byte
  verify the resulting byte isn't 0
  sleep 1
This block is then RSA encrypted and exchanged with the server. From then on, all packets get encrypted with this RC4 key. One interesting thing also, is that the game doesn't use RC4 as a continuous stream cipher, instead each packet resets the RC4 cipher to the initial state. This stems from the fact that the game can use UDP for communication and therefor needs to handle the case where packetloss occurs, which would desync the state, but it also makes this less secure. I'm not an expert in cryptography, but I'm sure this enables some interesting crypto attacks to decipher the content. From what I've read, the first few bytes of RC4 are already less random than they should be, which is why it's suggested to advance the RC4 state a couple of bytes before actually using it on your data, which this game doesn't do. Couple that with knowledge of some of the payloads' fixed bytes and I'm sure a real cryptographer can decipher a stream without much effort. Now there's 1 thing they did to try and counter some of this. Instead of starting the packet encrypt from the first byte of the packet, they start it from the middle of the packet, which helps a bit with the known byte value issue.
They are also feeding back the input into the RC4 state, by incrementing the j variable by the unencrypted input byte.

Another issue with just using the rdtsc instruction to generate random data, is that this instruction can be made priviledged by setting the TSD flag in CR4, ie. cause a system trap to occur when executed in userspace / ring3, which means there's full control over what this RC4 key generator produces without even having to alter the game binary or redirecting system APIs. Example code to do something like this, can be easily found, ie. here.