Archive

Archive for the ‘Game Hacking’ Category

Messing with Protocols: Reverse Engineering (2/3)

June 1st, 2011 No comments

Some prerequisite words: The networking code is aggressively optimized and this post will be extremely difficult to comprehend without decent knowledge of assembly and following along in a debugger. Below is my analysis of how a chat packet is constructed within the game, which was analyzed on a running instance with OllyDbg. Also, the knowledge contained in post isn’t necessarily needed for being able to forge packets across an established in-game connection.

The process begins by trying to find out where the game grabs the chat from. Logically, to build a chat packet, there needs to be some chat. This should either be the starting point or near to the starting point of building the chat packet to send. Techniques on finding out this starting point are situational. For example, if the chat were entered directly from some input box, it might be wise to breakpoint calls to GetDlgItemText or something similar and follow from there. For this, I chose the approach of setting a breakpoint on sendto and following the call stack backwards. The packet can be fully inspected on the call to sendto as shown below:

As an aside, this is also a good place to test for things like data checksums or even possible exploits in the protocol. Checking for data checksums is pretty easy — if one of those unknown fields in the packet is a checksum, then modifying the data but keeping the checksum the same will make the receiving client report an error and/or not display the chat. Since it was possible to modify the text and still have it appear on the other side, you can conclude that no data checksum is present (or the receiving code doesn’t check it). Additionally, modifying the length of the chat also allows the chat to get through. This is more interesting because there actually is a checksum on the length appended to the packets. Having looked over the recvfrom code, which won’t be discussed in this post, I will just say that the checksum is not checked by the game. There are other things to check for like overflows which can be invoked by setting the chat length to 0xFF and sending chat greater than 0xFF in size to see if the game parses the packet correctly or not. Overall, I didn’t find anything too interesting that didn’t solely cause my own instance (the one sending the packets) of the game to crash.
Back on topic however, the call stack at sendto is shown below:

The goal is to find out where the packet is built, so the best place to look is the furthest back. Checking DPLAYX.6E2E6333 reveals the following data at [ESP+14]:

which shows a chat packet containing the header. This means that it is necessary to check even further back. The next step is to look at the call from DPLAYX.6E2DCBBA. The call is shown below:

6E2DCBAC   6A 01            PUSH 1
6E2DCBAE   57               PUSH EDI
6E2DCBAF   53               PUSH EBX
6E2DCBB0   FF75 14          PUSH DWORD PTR SS:[EBP+14]
6E2DCBB3   FF75 F8          PUSH DWORD PTR SS:[EBP-8]
6E2DCBB6   FF75 1C          PUSH DWORD PTR SS:[EBP+1C]
6E2DCBB9   50               PUSH EAX
6E2DCBBA   E8 74970000      CALL DPLAYX.6E2E6333

Setting a breakpoint on this shows that the fully built packet is stored in EBX. Tracing backwards up the function, the chat is loaded into EBX by

6E2DCB1E   8B5D 18          MOV EBX,DWORD PTR SS:[EBP+18]

which means it’s necessary to go even further backwards since the packet is still fully built at this point. OllyDbg isn’t too great at keeping track of call stacks when the function isn’t called directly. Setting a breakpoint at the top of the function and checking the call stack showed that nothing called it, which definitely is not correct. The easiest approach is to inspect the stack manually for the point of return. When EBP is set up, the stack looks like the following:

That address leads to the following function, with the call at 0x005D356D:

005D3540  /$ 8B91 10470000  MOV EDX,DWORD PTR DS:[ECX+4710]
005D3546  |. 33C0           XOR EAX,EAX
005D3548  |. 85D2           TEST EDX,EDX
005D354A  |. 75 24          JNZ SHORT aoc1_-_C.005D3570
005D354C  |. 8B5424 14      MOV EDX,DWORD PTR SS:[ESP+14]
005D3550  |. A1 84027900    MOV EAX,DWORD PTR DS:[790284]
005D3555  |. 52             PUSH EDX
005D3556  |. 8B5424 14      MOV EDX,DWORD PTR SS:[ESP+14]
005D355A  |. 52             PUSH EDX
005D355B  |. 8B5424 14      MOV EDX,DWORD PTR SS:[ESP+14]
005D355F  |. 8B08           MOV ECX,DWORD PTR DS:[EAX]
005D3561  |. 52             PUSH EDX
005D3562  |. 8B5424 14      MOV EDX,DWORD PTR SS:[ESP+14]
005D3566  |. 52             PUSH EDX
005D3567  |. 8B5424 14      MOV EDX,DWORD PTR SS:[ESP+14]
005D356B  |. 52             PUSH EDX
005D356C  |. 50             PUSH EAX
005D356D  |. FF51 68        CALL DWORD PTR DS:[ECX+68]
005D3570     C2 1400        RETN 14

This is beginning to lead in the right direction since the call is made directly from the game instead of an additional library. Additionally, this function is only called when chat is to be sent. All other ones prior to this were called when any packet was to be sent. The chat is loaded into EDX at the following instruction:

005D355A  |. 52             PUSH EDX

The packet is still fully built at this point, but the search is almost over. The problem and approach are still the same, but now its been heavily isolated. The call stack from this point should contain functions that deal with collecting data and constructing the appropriate packet, instead of networking functions in the DirectPlay and Winsock libraries. Taking the same approach as before and setting a breakpoint at the top of the function shows the following call stack:

Looking at 0x005DC6720, one of the further functions down the call stack, begins to show some promise. When this function is entered, the chat string is held in the EAX register. It can be modified and the changes carry on through to the sendto function. This means that it’s not a function working on a temporary copy of the buffer, but that it holds the “real” one that will be written into the chat packet. This seems like a good starting point since there is no sign of any packet header being built. Additionally, inspecting the other functions up the call stack from 0x005DC720 shows that some of them display debug messages dealing with packets and chat headers. This is also a good sign that the real reversing should begin here.

What I personally prefer doing is following the code flow in OllyDbg then highlighting the executed code path in IDA Pro. The assembly listings from IDA will be shown in the code blocks to follow. The function starts at 0x005D6720:

.text:005D6720 ; int __stdcall send_normal(char *Str)
.text:005D6720 send_normal     proc near               ; CODE XREF: sub_4FD360+BDFp
.text:005D6720                                         ; sub_5A6C90+154p ...
.text:005D6720
.text:005D6720 broadcast       = dword ptr -0Ch
.text:005D6720 var_8           = dword ptr -8
.text:005D6720 var_4           = word ptr -4
.text:005D6720 Str             = dword ptr  4
.text:005D6720
.text:005D6720                 sub     esp, 0Ch
.text:005D6723                 mov     eax, 59595959h
.text:005D6728                 push    esi
.text:005D6729                 mov     [esp+10h+broadcast], eax
.text:005D672D                 mov     esi, ecx
.text:005D672F                 mov     [esp+10h+var_8], eax
.text:005D6733                 mov     [esp+10h+var_4], ax
.text:005D6738                 mov     eax, [esi+10E4h] ; number of other players in game
.text:005D673E                 test    eax, eax
.text:005D6740                 jnz     short loc_5D6780

The first thing to notice is that no stack frame is set up. This is the beginning of a lot of incoming optimized code. Everything function to come will not set up a stack frame and will work directly relative to ESP. The next thing to notice is that the value 0x59595959 is moved into EAX, which is then moved into [ESP+0x4]. Why 0x59595959? Looking back at the previous example packets, there were eight bytes devoted to who can see the packet. These were set to either Y or N depending on whether the target player is supposed to display the message or not. 0x59 happens to be the ASCII code for ‘Y’, so the beginning of this function sets up to send a message to all players, i.e. the broadcast field in the packet will be YYYYYYYY (or 0x59 0x59 … 0x59). [ESI+0x10E4] holds the number of other players in the game. This is moved into EAX and checked for zero. Assuming there is at least one additional player, the code jumps to 0x005D6780. The case where no other player is in game won’t be discussed in-depth except that in that case no packets are sent and the text is only displayed on the screen. Continuing on at 0x005D6780 is the following block:

.text:005D6780 loc_5D6780:                             ; CODE XREF: send_normal+20j
.text:005D6780                 mov     eax, [esp+14h]
.text:005D6784                 mov     edx, [esi+10E0h]
.text:005D678A                 lea     ecx, [esp+10h+broadcast]
.text:005D678E                 push    eax             ; chat string
.text:005D678F                 push    ecx             ; broadcast audience
.text:005D6790                 push    edx             ; player_index
.text:005D6791                 mov     ecx, esi
.text:005D6793                 call    sub_5D67A0
.text:005D6798                 pop     esi
.text:005D6799                 add     esp, 0Ch
.text:005D679C                 retn    4
.text:005D679C send_normal     endp

Looking at this is just a matter of stepping over in OllyDbg. The function at 0x005D67A0 is called with the player index, the broadcast audience, and the chat message as parameters. This function is a bit longer and more complicated. The first block is shown below:

.text:005D67A0 ; int __stdcall sub_5D67A0(int player_index, int chat_message, char *Str)
.text:005D67A0 sub_5D67A0      proc near               ; CODE XREF: .text:004A8961p
.text:005D67A0                                         ; sub_4A8970+5Bp ...
.text:005D67A0
.text:005D67A0 var_114         = byte ptr -114h
.text:005D67A0 var_113         = byte ptr -113h
.text:005D67A0 chat_length     = dword ptr -108h
.text:005D67A0 var_104         = byte ptr -104h
.text:005D67A0 Dest            = byte ptr -103h
.text:005D67A0 var_4           = byte ptr -4
.text:005D67A0 player_index    = dword ptr  4
.text:005D67A0 chat_message    = dword ptr  8
.text:005D67A0 Str             = dword ptr  0Ch
.text:005D67A0
.text:005D67A0                 sub     esp, 114h
.text:005D67A6                 xor     eax, eax
.text:005D67A8                 push    ebx
.text:005D67A9                 push    ebp
.text:005D67AA                 mov     ebp, ecx
.text:005D67AC                 push    esi
.text:005D67AD                 mov     ecx, [esp+120h+player_index]
.text:005D67B4                 push    edi
.text:005D67B5                 mov     ax, [ebp+12DCh] ; maximum number of players
.text:005D67BC                 cmp     ecx, eax
.text:005D67BE                 jbe     short loc_5D67D2

This code will be tricky to go through because things will be referenced through EBP and ESP. The important immediate thing to note is that EBP takes the value of ECX, which had ESI moved into it prior to the function call. As usual, no stack frame is set up. All that this code does is compare the index of the player sending the chat (stored in [EBP+0x12DC]) with the maximum number of players allowed in the game. The error condition is that the player index is greater than the maximum number allowed (e.g. player 9 is trying to send a message in an 8 player game). Assuming no error, the jump to 0x005D67D2 is taken. This is a pretty small block which performs an unusual check:

.text:005D67D2 loc_5D67D2:                             ; CODE XREF: sub_5D67A0+1Ej
.text:005D67D2                 mov     ebx, [esp+124h+Str]
.text:005D67D9                 push    ebx             ; Str
.text:005D67DA                 call    _atoi
.text:005D67DF                 mov     esi, 1
.text:005D67E4                 add     esp, 4
.text:005D67E7                 cmp     [ebp+12DCh], si ; [ebp+12DCh] holds number of players
.text:005D67EE                 mov     edi, eax
.text:005D67F0                 jb      loc_5D6883

The purpose of the call to atoi is to check whether a taunt has been entered. Taunts are represented in chat purely by numbers, so atoi will return non-zero if that is the case. The code then continues to check whether more than one player is in the game. This is to determine whether it’s necessary to build a packet or not. Assuming more than one player is in the game, the jump to 0x005D6883 is not taken. A loop is then entered. The important parts of the loop are reproduced below. These are the instructions that are executed when more than one player is to receive some chat.

.text:005D67F6 loc_5D67F6:                             ; CODE XREF: sub_5D67A0+DDj
.text:005D67F6                 push    esi             ; begin loop to see who is allowed to see message
.text:005D67F7                 mov     ecx, ebp
.text:005D67F9                 call    can_player_see
.text:005D67FE                 test    eax, eax
.text:005D6800                 jnz     short loc_5D680E ; player allowed to see message
.text:005D6802                 push    esi             ; player number
.text:005D6803                 mov     ecx, ebp
.text:005D6805                 call    sub_5D9720
.text:005D680A                 test    eax, eax
.text:005D680C                 jz      short loc_5D686C
.text:005D680E
.text:005D680E loc_5D680E:                             ; CODE XREF: sub_5D67A0+60j
.text:005D680E                 mov     ecx, [esp+124h+chat_message] ; player allowed to see message
.text:005D6815                 cmp     byte ptr [esi+ecx], 59h
.text:005D6819                 jnz     short loc_5D686C
.text:005D681B                 mov     edx, dword_7912A0 ; jump not taken, player allowed to see message
.text:005D6821                 mov     [esp+esi+124h+var_113], 59h ; allowed flag
.text:005D6826                 mov     eax, [edx+424h]
.text:005D682C                 test    eax, eax
.text:005D682E                 jz      short loc_5D6871
.text:005D6871
.text:005D6871 loc_5D6871:                             ; CODE XREF: sub_5D67A0+8Ej
.text:005D6871                                         ; sub_5D67A0+98j ...
.text:005D6871                 xor     eax, eax
.text:005D6873                 inc     esi             ; see if next player is allowed to see message
.text:005D6874                 mov     ax, [ebp+12DCh] ; maximum number of players in game
.text:005D687B                 cmp     esi, eax
.text:005D687D                 jbe     loc_5D67F6      ; begin loop to see who is allowed to see message
.text:005D6883
.text:005D6883 loc_5D6883:                             ; CODE XREF: sub_5D67A0+50j
.text:005D6883                 mov     eax, [ebp+10E4h] ; total number of players in game
.text:005D6889                 test    eax, eax
.text:005D688B                 jnz     loc_5D6915

The can_player_see function at 0x005D96E0 just returns 1 or 0 depending on whether the player can see the message. What this loop basically does is decide who is going to see this message. The YYY…Y buffer that was passed in to this function gets modified here according to which player can see the message. The following two instructions set the appropriate byte:

.text:005D6821                 mov     [esp+esi+124h+var_113], 59h ; allowed flag

or

.text:005D686C                 mov     [esp+esi+124h+var_113], 4Eh ; not allowed flag

The loop continues for eight iterations, the maximum number of players in the game. Once this loop is done, the part of the packet which will hold who can see the message is ready. Once the loop exits, the following code blocks are executed:

.text:005D6883 loc_5D6883:                             ; CODE XREF: sub_5D67A0+50j
.text:005D6883                 mov     eax, [ebp+10E4h] ; total number of players in game
.text:005D6889                 test    eax, eax
.text:005D688B                 jnz     loc_5D6915
.text:005D6915 ; ---------------------------------------------------------------------------
.text:005D6915
.text:005D6915 loc_5D6915:                             ; CODE XREF: sub_5D67A0+EBj
.text:005D6915                                         ; sub_5D67A0+164j
.text:005D6915                 mov     ecx, [ebp+10E0h]
.text:005D691B                 cmp     [esp+ecx+124h+var_113], 59h
.text:005D6920                 jnz     short loc_5D6957 ; EDI holds chat string
.text:005D6922                 mov     eax, [esp+124h+player_index]
.text:005D6929                 mov     edx, [ebp+12CCh] ; username sending chat
.text:005D692F                 mov     ecx, [ebp+18h]
.text:005D6932                 push    0
.text:005D6934                 push    0
.text:005D6936                 push    eax
.text:005D6937                 shl     eax, 7
.text:005D693A                 add     edx, eax        ; EDX holds username
.text:005D693C                 push    ebx             ; EBX holds chat
.text:005D693D                 push    edx
.text:005D693E                 call    sub_5E2780
.text:005D6943                 mov     eax, dword_78BF34
.text:005D6948                 push    ebx
.text:005D6949                 push    offset aLocalChatAddS ; "Local chat add: %s"
.text:005D694E                 push    eax
.text:005D694F                 call    nullsub_1       ; debug function?
.text:005D6954                 add     esp, 0Ch
.text:005D6957
.text:005D6957 loc_5D6957:                             ; CODE XREF: sub_5D67A0+180j
.text:005D6957                 mov     edi, ebx        ; EDI holds chat string
.text:005D6959                 or      ecx, 0FFFFFFFFh
.text:005D695C                 xor     eax, eax
.text:005D695E                 repne scasb             ; Calculates length of string
.text:005D6960                 not     ecx
.text:005D6962                 dec     ecx             ; ECX holds number of characters
.text:005D6963                 cmp     ecx, 0FFh
.text:005D6969                 jbe     short loc_5D6972 ; Calculates length of string again

There isn’t anything too special about this block. There is a call to 0x005E2780, which is a huge and complicated function. Fortunately, it doesn’t do anything related to modifying the chat or building a packet — so it doesn’t have to be analyzed. Other than that there is nothing going on except for calculating the length of the string. This is compared against 0xFF, which is the maximum number of characters allowed. Normal execution continues into the following blocks:

.text:005D6972 ; ---------------------------------------------------------------------------
.text:005D6972
.text:005D6972 loc_5D6972:                             ; CODE XREF: sub_5D67A0+1C9j
.text:005D6972                 mov     edi, ebx        ; Calculates length of string again
.text:005D6974                 or      ecx, 0FFFFFFFFh
.text:005D6977                 xor     eax, eax
.text:005D6979                 repne scasb
.text:005D697B                 not     ecx
.text:005D697D                 dec     ecx
.text:005D697E
.text:005D697E loc_5D697E:                             ; CODE XREF: sub_5D67A0+1D0j
.text:005D697E                 mov     dl, byte ptr [esp+124h+player_index]
.text:005D6985                 mov     [esp+124h+chat_length], ecx ; Chat length added to buffer
.text:005D6989                 inc     ecx
.text:005D698A                 lea     eax, [esp+124h+Dest]
.text:005D698E                 push    ecx             ; Count
.text:005D698F                 push    ebx             ; Source
.text:005D6990                 push    eax             ; Dest
.text:005D6991                 mov     [esp+130h+var_114], dl ; Player number who sent message
.text:005D6995                 call    _strncpy
.text:005D699A                 mov     ecx, [ebp+1E3Ch] ; 3?
.text:005D69A0                 mov     edx, [esp+130h+chat_length]
.text:005D69A4                 add     esp, 0Ch
.text:005D69A7                 cmp     ecx, 3
.text:005D69AA                 setz    cl              ; CL = 1
.text:005D69AD                 add     edx, 16h
.text:005D69B0                 push    0
.text:005D69B2                 lea     eax, [esp+128h+var_114]
.text:005D69B6                 push    edx             ; Chat length + 0x16
.text:005D69B7                 push    eax             ; Partial packet. Contains chat flag, chat length, who is allowed to see, and message
.text:005D69B8                 mov     [esp+130h+var_104], cl
.text:005D69BC                 push    43h
.text:005D69BE                 push    0
.text:005D69C0                 mov     ecx, ebp
.text:005D69C2                 mov     [esp+138h+var_4], 0
.text:005D69CA                 call    sub_5D7BC0
.text:005D69CF                 mov     ecx, [ebp+1608h]
.text:005D69D5                 mov     esi, eax
.text:005D69D7                 push    offset aTxchat  ; "TXChat()"
.text:005D69DC                 push    esi
.text:005D69DD                 call    sub_5DF900
.text:005D69E2                 mov     eax, esi
.text:005D69E4                 pop     edi
.text:005D69E5                 pop     esi
.text:005D69E6                 pop     ebp
.text:005D69E7                 pop     ebx
.text:005D69E8                 add     esp, 114h
.text:005D69EE                 retn    0Ch
.text:005D69EE sub_5D67A0      endp

Prior to entering this code block the packet buffer contains only who is allowed to see the message. The actual packet buffer is stored relative to ESP and the data will be written directly there. There are some parts that are difficult to analyze like magic values appearing out of nowhere, i.e., [EBP+0x1E3C] holding the value of 3. These don’t affect understanding the code too much unless they play some vital role in how the actual packet will be built (the value is a flag parameter for a function, etc.). With the code above, the the CL register is set to 1 since 3 == 3, and is written into the packet buffer. Fortunately, one beneficial thing about this optimized code is that it’s easy to see where the packet is being built. The writes into [ESP+xx]¬† hold the buffer for the packet, which can be verified by inspecting it in the dump with OllyDbg. Checking all places where this occurs and seeing what is being written, the packet will have the following fields before entering the function at 0x005D7BC0: A field set to 0x1 (the CL value being written in), who is allowed to see the chat, the chat message itself, and an additional special value 0xDC. This value is always found in the same field and always has the same value. A view of the packet from the dump is shown below:

The call to 0x005D7BC0 will add the remaining fields of the packet (the two supposed counter values, and fields marked as unknown in the first post). Since this function is pretty big, I won’t duplicate the entire thing here, but only relevant parts — this post is meant to be followed along with in a disassembler after all. This function allocates a new block of memory and returns the entire packet to send (excluding the fields added by DirectPlay’s networking code). The “second counter” bytes are written in by the instructions listed below:

.text:005D7C1A loc_5D7C1A:                             ; CODE XREF: sub_5D7BC0+39j
.text:005D7C1A                 push    0Ch             ; unsigned int
.text:005D7C1C                 call    ??2@YAPAXI@Z    ; operator new(uint)
.text:005D7C21                 mov     edx, [esp+34h+arg_C]
.text:005D7C25                 mov     ecx, [ebp+4714h] ;time stamp
.text:005D7C2B                 mov     edi, eax
.text:005D7C2D                 mov     al, [ebp+1DD0h] ; 1
.text:005D7C33                 add     esp, 4
.text:005D7C36                 add     ecx, edx
.text:005D7C38                 test    al, al
.text:005D7C3A                 mov     [esp+30h+Memory], edi
.text:005D7C3E                 mov     [ebp+4714h], ecx ; 0x51E
.text:005D7C44                 jz      short loc_5D7C7A
.text:005D7C46                 mov     ecx, [ebp+1DA0h] ; Retrieve second counter
.text:005D7C4C                 mov     [edi+8], ecx    ; Write value into packet
.text:005D7C4F                 mov     eax, [ebp+10E0h] ; player position
.text:005D7C55                 mov     ecx, [ebp+1DA0h] ; second counter value
.text:005D7C5B                 mov     [ebp+eax*4+1DE4h], ecx
.text:005D7C62                 mov     eax, [ebp+1DA0h] ; Get second counter value
.text:005D7C68                 inc     eax             ; Increment it for next packet
.text:005D7C69                 mov     [ebp+1DA0h], eax ; Write new value back in
.text:005D7C6F                 mov     eax, 0Ch
.text:005D7C74                 mov     [esp+30h+var_20], eax
.text:005D7C78                 jmp     short loc_5D7C89
.text:005D7C89
.text:005D7C89 loc_5D7C89:                             ; CODE XREF: sub_5D7BC0+B8j
.text:005D7C89                 lea     ecx, [eax+edx]  ; size of header + data
.text:005D7C8C                 cmp     ecx, 0FA0h      ; maximum packet size
.text:005D7C92                 mov     [esp+30h+var_1C], ecx ; write in full size
.text:005D7C96                 jbe     short loc_5D7CB3

Again there are some magic values that seemingly appear out of nowhere. There are some more familiar ones like [EBP+0x10E0], which was shown in previous functions as storing the player index. The value of the counter is kept at [EBP+0x1DA0], which is written into the packet through EDI. The timestamp bytes are also written in, which are apparently kept at [EBP+0x4714]. The code in the second block just grabs the counter, writes it to the packet buffer, and increments it for the next time it is used. The next block writes in the size of the packet so far. This will be a check to make sure that the header and data do not exceed the maximum length allowed for a chat packet. The next field is an unknown field that is written by:

.text:005D7CB3
.text:005D7CB3 loc_5D7CB3:                             ; CODE XREF: sub_5D7BC0+D6j
.text:005D7CB3                 xor     eax, eax
.text:005D7CB5                 mov     byte ptr [edi+1], 0
.text:005D7CB9                 mov     byte ptr [edi], 0
.text:005D7CBC                 mov     al, [ebp+1E74h] ; Number of players
.text:005D7CC2                 mov     ecx, [ebp+10C8h] ; 2?
.text:005D7CC8                 lea     ebx, [ebp+1DA8h] ; 4?
.text:005D7CCE                 add     eax, ecx
.text:005D7CD0                 mov     [esp+30h+var_14], eax
.text:005D7CD4                 mov     [edi+4], eax    ; 06 00 00 00 added here

This writes in 06 00 00 00 to the packet, which comes from adding [EBP+0x10C8] and [EBP+0x1DA8] together. Where these two things come from, I’m not entirely quite sure. However, they remain constant across all packets regardless of size, player index, and so on, so it’s not too important for being able to forge packets. The other counter value can be found at

.text:005D7D22                 mov     ecx, [esp+30h+var_14] ; Full packet size
.text:005D7D26                 push    ecx
.text:005D7D27                 mov     ecx, ebp
.text:005D7D29                 call    sub_5D7B50
.text:005D7D2E                 mov     [edi+1], al     ; Counter value
.text:005D7D31                 mov     ecx, [ebp+1E3Ch] ; 3?
.text:005D7D37                 cmp     ecx, 5
.text:005D7D3A                 jz      short loc_5D7D6C
.text:005D7D3C                 test    al, al
.text:005D7D3E                 jnz     short loc_5D7D6C

in the call to 0x005D7B50, which returns the counter byte. This can be seen here

.text:005D7B6F ; ---------------------------------------------------------------------------
.text:005D7B6F
.text:005D7B6F loc_5D7B6F:                             ; CODE XREF: sub_5D7B50+Cj
.text:005D7B6F                 mov     al, byte ptr dword_790FAC ; Get counter byte
.text:005D7B74                 inc     al              ; Increment counter byte
.text:005D7B76                 cmp     al, 0FFh        ; Compare with max allowed
.text:005D7B78                 mov     byte ptr dword_790FAC, al ; Write value back
.text:005D7B7D                 jb      short loc_5D7BA3

which just gets the byte, increments it, and resets it if it’s greater than 0xFF. The last important block of code is shown below:

.text:005D7D6C
.text:005D7D6C loc_5D7D6C:                             ; CODE XREF: sub_5D7BC0+17Aj
.text:005D7D6C                                         ; sub_5D7BC0+17Ej
.text:005D7D6C                 mov     eax, [esp+30h+var_1C] ; Full packet size
.text:005D7D70                 mov     [edi], bl       ; Packet type 60
.text:005D7D72                 inc     eax
.text:005D7D73                 push    eax             ; unsigned int
.text:005D7D74                 call    ??2@YAPAXI@Z    ; operator new(uint)
.text:005D7D79                 mov     ebx, eax        ; Buffer size of the packet header + data
.text:005D7D7B                 mov     eax, [esp+34h+var_20] ; 0xC?
.text:005D7D7F                 mov     ecx, eax
.text:005D7D81                 mov     esi, edi
.text:005D7D83                 mov     edx, ecx
.text:005D7D85                 mov     edi, ebx
.text:005D7D87                 shr     ecx, 2
.text:005D7D8A                 rep movsd               ; Packet minus session key is written here
.text:005D7D8C                 mov     ecx, edx
.text:005D7D8E                 add     esp, 4
.text:005D7D91                 and     ecx, 3
.text:005D7D94                 mov     [esp+30h+var_10], ebx
.text:005D7D98                 rep movsb
.text:005D7D9A                 mov     ecx, [esp+30h+arg_C]
.text:005D7D9E                 test    ecx, ecx
.text:005D7DA0                 jz      short loc_5D7DB7

Prior to entering this block, the packet is fully built. This is responsible for creating the buffer for the full packet to send and copying the contents in there. There’s not much more to it at this point. Looking down the function, it will call into another function which in turn calls into DirectPlay (seen earlier in this post).
The entire explanation has basically been following across the call stack and seeing how the chat input is transformed from it’s initial stage into a fully built packet. The specific knowledge gained may not have been too great — there are still those unknown fields — however, it was useful to see that there are special checksums or integrity checks performed on the data which will go in to the packet. Also, it was possible to learn how those counters in the packet function, how their values change, and if their values have any effect on how data will be transmitted. I don’t expect this explanation to be incredibly clear since it was written over a period of a few days, but these are some notes that I wanted to publish online both for my records and as a demonstration of how difficult and confusing it can be to even reverse one specific type of packet in a protocol. Unfortunately, the code is extremely optimized so this post may not serve as a great starting point into reversing protocols altogether, but the general idea should be the same of finding out where and how certain input is transformed into a transmittable packet.

A downloadable PDF of this post can be found here.

Categories: Game Hacking, Reverse Engineering Tags:

Messing with Protocols: Preliminary (1/3)

May 27th, 2011 No comments

This next series of posts will focus on looking at a game’s protocol. Specifically, the packet structure and some basic steps into the world of packet reversing. I will focus on explaining how a specific packet (a chat packet) is built in-game and how understanding the packet structure can let someone do some fun and unexpected things. It should be noted that this won’t be an article in server emulation as that is much too complex and time consuming to both perform and write about. The steps and methodologies discussed though can aid in beginning to fully reverse a protocol and begin a project in server emulation. This whole series will be broken down into three parts:

  • A preliminary post (this one) discussing how to perform a high level inspection of a protocol.
  • Reverse engineering the target application to see where and how a specific packet is built.
  • Example programs that could be written to send your own packets or modify parts of incoming/outgoing packets.

To start off, the target will be Age of Empires II: The Conquerors Expansion. This was chosen because the chat packets of the protocol are unencrypted so there won’t be any large sidetrack about hunting down encryption keys or reversing algorithms. There are other factors like the game being dead (developing studio disbanded), and it being one of the few multiplayer games that I own. That said, it’s time for some analysis. One of the better tools for this job is WPE Pro. It’s extremely easy to use and provides a simple interface that displays everything that is needed. To get started, I created a LAN game with myself and used WPE to log packets on one instance. Below is an example of some chat packets that were sent. These can be analyzed for patterns and guesses at the different parts of it can be taken and later verified or discarded. The hex dump of the packets is shown below, with the sent chat in blue and the changes between the packets highlighted in red:
D8 26 D9 16 00 00 00 00 43 17 00 00 06 00 00 00 E7 07 00 00 01 DC 59 59 4E 4E 4E 4E 4E 4E 32 00 01 00 00 00 01 41 00 00 24 DC 18
D8 26 D9 16 00 00 00 00 43 18 23 02 06 00 00 00 E8 07 00 00 01 DC 59 59 4E 4E 4E 4E 4E 4E 32 00 02 00 00 00 01 41 41 00 24 DC 18 00
D8 26 D9 16 00 00 00 00 43 19 18 00 06 00 00 00 E9 07 00 00 01 DC 59 59 4E 4E 4E 4E 4E 4E 32 00 03 00 00 00 01 41 41 41 00 DC 18 00 80
D8 26 D9 16 00 00 00 00 43 1A 18 00 06 00 00 00 EA 07 00 00 01 DC 59 59 4E 4E 4E 4E 4E 4E 32 00 04 00 00 00 01 41 41 41 41 00 18 00 80 DC
D8 26 D9 16 00 00 00 00 43 1B 23 02 06 00 00 00 EB 07 00 00 01 DC 59 59 4E 4E 4E 4E 4E 4E 32 00 05 00 00 00 01 41 41 41 41 41 00 00 80 DC 54
These packets show sending “A”, “AA”, “AAA”, “AAAA”, and “AAAAA” to the chat, which can be seen (0x41 characters). One thing to immediately note is that the name of the player sending the chat is not contained in the packet. That means that there is some field in the packet which denotes who is sending the packet. There also appear to be a few flags that serve as counters. The first packet contains 0x17 and 0xE7, the next one increments these bytes to 0x18 and 0xE8, the one afterwards to 0x19 and 0xE9, and so on. There is also a lone field in the packet which matches the size of the chat being sent. Lastly, there are some unknown values which seem to change with each packet sent. To get a better understanding of things, it is better to log packets over multiple instances/connections. The game was restarted and the same five packets were sent. Reproduced below are the five packets with their differences and chat highlighted. Additionally, the logging was done from sending chat as the second player in the game session.
DD BF 35 17 00 00 00 00 43 07 00 00 06 00 00 00 A7 0F 00 00 02 DC 59 59 4E 4E 4E 4E 4E 4E 4B 00 01 00 00 00 01 41 00 00 24 DC 18
DD BF 35 17 00 00 00 00 43 08 3D 02 06 00 00 00 A8 0F 00 00 02 DC 59 59 4E 4E 4E 4E 4E 4E 4B 00 02 00 00 00 01 41 41 00 24 DC 18 00
DD BF 35 17 00 00 00 00 43 09 18 00 06 00 00 00 A9 0F 00 00 02 DC 59 59 4E 4E 4E 4E 4E 4E 4B 00 03 00 00 00 01 41 41 41 00 DC 18 00 80
DD BF 35 17 00 00 00 00 43 0A 18 00 06 00 00 00 AA 0F 00 00 02 DC 59 59 4E 4E 4E 4E 4E 4E 4B 00 04 00 00 00 01 41 41 41 41 00 18 00 80 DC
DD BF 35 17 00 00 00 00 43 0B 3D 02 06 00 00 00 AB 0F 00 00 02 DC 59 59 4E 4E 4E 4E 4E 4E 4B 00 05 00 00 00 01 41 41 41 41 41 00 00 80 DC 54
Changes appeared to have happened within the expected offsets in the packets. Comparing differences between two packets from two different sessions:
D8 26 D9 16 00 00 00 00 43 1B 23 02 06 00 00 00 EB 07 00 00 01 DC 59 59 4E 4E 4E 4E 4E 4E 32 00 05 00 00 00 01 41 41 41 41 41 00 00 80 DC 54
DD BF 35 17 00 00 00 00 43 0B 3D 02 06 00 00 00 AB 0F 00 00 02 DC 59 59 4E 4E 4E 4E 4E 4E 4B 00 05 00 00 00 01 41 41 41 41 41 00 00 80 DC 54
The 0x1B and 0x0B flags are highlighted differently because they’re supposed to be the same. There were some intermediate messages sent between testing in one of the sessions and it threw off the counter. Everything else should be normal. One of the “unexpected” changes was that 0x01 changed to 0x02 and 0x32 changed to 0x4B. Since the only change aside from a new session was that the sending player was in the second player slot, it might be reasonable to guess that the byte that changed from 0x01 to 0x02 holds the number of the player who is sending the chat. The change in the other byte is unknown. The other unexpected change was that the first four bytes of the packet also changed. For the sake of not having to explain, I’ll simply mention that the first four, possibly eight, bytes appear to be a session key since they precede all packets sent throughout the game (not just chat ones). The actual value of the key is calculated external to the game, in the DirectPlay networking library. Finding out how the key is negotiated is still something that I am working on and won’t be covered in this series of posts — perhaps at a future date as my progress develops. The downside to not knowing how to calculate this is that in order to send custom packets to the client the connection must already exist. Obtaining the key is not really a problem however as sendto/recvfrom can be hooked and the key stored. The next thing to note is about the last four bytes of the packet. These are also external to game and appended by DirectPlay. From my testing, these four bytes appear to be a checksum on the size of the packet. For example, sending “a”, “b”, “q”, “$”, or any one character chat text will append 00 24 DC 18 to the packet. All two character texts have the same bytes appended at the end, and so on. The last thing is about the eight bytes after the player index. In the samples these bytes 0x59 and 0x4E. For a high level analysis, it is important to test as many things as possible. The in-game chat has three options: all (default), team, and enemy. Testing sending messages using these three options reveals that these eight bytes are the “audience” flags of who of the at most eight players in a game can see the chat message. Given that a majority of the packet has been understood and guessed at, this completes the high level preliminary analysis. A sample packet is shown below and guessed at or known fields are highlighted.
DD BF 35 17 00 00 00 00 43 0B 3D 02 06 00 00 00 AB 0F 00 00 02 DC 59 59 4E 4E 4E 4E 4E 4E 4B 00 05 00 00 00 01 41 41 41 41 41 00 00 80 DC 54

Red indicates a session key.
Blue indicates some sort of counter bytes.
Pink indicates the player sending the chat.
Green indicates who is to receive the message.
Yellow indicates the length of the chat string.
Grey indicates the chat string and the null terminator.
Teal indicates the trailing checksum.
Orange indicates unknown bytes that were constant across multiple sessions.
Black indicates unknown bytes that were variable across multiple sessions.

One last point to make is that at a high level, how some of these bytes are interpreted could be off. For example, the size of the packet shown as 0x05 could actually be given two bytes, 0x00 and 0x05 in the packet, making that orange unknown byte part of the size. The 0x06, 0x00, 0x00, 0x00 bytes could actually be a DWORD instead of four unique, unrelated properties, and so on. The high level analysis is good for getting started but the actual application will require reverse engineering to fully know what is going on. This will be the topic of the next post.

A downloadble PDF of this post can be found here.

Categories: Game Hacking, Reverse Engineering Tags:

Quick Post: Auto-updating with Signature Scanning

May 26th, 2011 No comments

One common problem with developing hacks or external modifications for games/applications is when the target application gets modified through patches, new versions, or so on. This might render offsets, structures, functions, or anything important that is used in the hack as useless if it is hardcoded. For example, assume that the hack puts a hook on a function at 0x1234ABCD. One day, a new version of the application is released and the new compiled version no longer has this function at 0x1234ABCD, but it’s at some different address, 0x12345678. Now the hack no longer works, and in the worst case, even crashes the application when used. This becomes annoying because some applications are frequently updated, which in turn requires frequent updates on the part of the hack developer. Even if the updates aren’t too frequent, it can be unnecessarily inconvenient to hunt down where the structures, functions, and so on ended up. One solution to this is called signature scanning. This technique is nothing new or special and has been used by both hack developers and anti-virus programs for many years (anti-viruses probably much longer than in hacks). It relies on finding parts of a program through scanning for certain byte patterns. For example, anti-virus programs rely partially on signature scanning when they scan files since each virus or variant can be identified with a sequence of bytes unique to it. Byte strings from scanned programs are taken and hashed. This hash is compared with known virus hashes in a database and if there is a match then there is a good chance that the application is a virus or has been infected. This of course ignores additional heuristics and scanning methods incorporated into anti-virus programs, but is still at a very basic level a key component of how they all work. This same methodology can be applied to developing game hacks or external modifications to applications in general since functions, structures, and so on also have unique byte patterns identifying them.

Shown above is part of a function that could serve as a signature. No other function in the application performs this unique set of instructions so assuming that this function does not change (the actual code within it is modified or things like new optimization settings or compilers being used) then it can always be identified with \x55\x8B\xEC\x51\x6A\x10\...\xD9\x59\x04 regardless of any updates of patches to the application. However, this technique is not without its downsides: scanning an entire file or image is costly in terms of speed. Thus, it is a pretty bad idea to develop a hack that scans an image for a signature each time it is loaded since that can slow things down a lot. What I personally do is keep an external config file that holds signatures and the offset (RVA) into the image at which they’re located. Then when a hack is loaded it can read in the config file and check that the signature exists where it’s supposed to. If it doesn’t then the hack will perform a scan on the whole image and write back into the config file where the new signature exists. This is only one way of doing it though so to each their own. Since the implementation is just searching for a substring, I feel that there’s really no need to put one here. Important things to note though for developing signature scanners:

  • Signature scanners should have some wildcard usage built in. Whether EAX, EBX and so on is used to hold a temporary value is irrelevant. For example, MOV EAX, 123 as a byte string is B823010000 and MOV EBX, 123 is BB23010000. The important part of those instructions is the 123 immediate value, so the B8 or BB byte is irrelevant. The signature can then be \x??\x23\x01\x00\x00. How \x?? is treated is implementation dependent.
  • Usually the most important parts of a signature are any references to other code, structures, local variables, etc. Getting a signature containing these will increase the chance of it being found. However, references to other code is a bit dangerous since relative distances can change between new versions of a target application.
  • A signature, by definition, should be unique. Using PUSH EBP ; MOV EBP, ESP is a bad idea.

A downloadable PDF of this post can be found here.

[Release] Age of Empires II: The Conquerors Expansion Stat Hack (Undetected)

March 19th, 2011 No comments

This is a prelude to an upcoming post on hardware breakpoints through structured and vectored exception handling:

I posted how to bypass Voobly’s anti-cheat a while back (hint: hardware breakpoints). I’ve had this hack developed since writing those articles but since I don’t play the game there is no point in keeping this lying around on my file system. That said, I’ll just release it. I didn’t write a loader for the DLL since there are hundreds out there such as Process Hacker which do the job quite well.
Usage: Inject the DLL to a running instance of Age of Empires II (preferably in the in-game lobby prior to a game starting). F5 toggles between modes, F6 resets the hack in case all players somehow were not captured — this actually should not happen unless the player has not done anything to modify their resource count. This works on single player and multiplayer and as of 9:00PM EST on 03/19/2011 is not detected by Voobly. I make no guarantees after this time and date. Enjoy!
Binary download: here

Categories: Game Hacking Tags:

Game Hacking: Age of Empires II (Part 2/?)

February 4th, 2011 No comments

This part will focus on how to draw player stats on the game screen. One obvious advantage to this over the previous article is that the player stats are directly in the game, thus there is no need to alt-tab out or play in windowed mode to see what the other players have. Additionally, a toggle feature will be added that allows the player to cycle through various modes to see different types of statistics on the others. The first step is to find a place where either some text, or more specifically, the players scores are drawn. The advantage to finding where the player scores are drawn is that player statistics will be drawn in a natural location and that they can correspond in color to the player. The first step is to think about how the player text is drawn on screen. There is always the player name, a colon followed by a space, and two numbers with a forward slash separating them. Searching for a format similar to this in the games referenced strings leads to what could be the right path.
A string with our desired format is found, and some other interesting strings which hint to drawing. Setting a breakpoint on where the “%s: %d/%d” string is referenced shows that it does in fact relate to the players¬† scores. The function that uses this is called on a timer continually to update the players scores on the screen. The image below shows what values are loaded in registers on the first and second call respectively.

The general gist of how the function works is that the player whose score is to be retrieved is loaded into the EAX register. The function flow continues until the score is retrieved. The score for the next player is retrieved while the string containing the name and score of the previous player is drawn on the screen. The process then continues for the next player and restarts while the game is active. Modifying the name on a call shows that this does indeed affect how the text is drawn on the screen

This can then be taken advantage of to draw what we want. Tracing exactly where the name gets drawn leads to the call from .text:0052107D.

.text:0052104C                 mov     eax, [esp+350h+var_330]
.text:00521050                 mov     ecx, [esp+350h+var_340]
.text:00521054                 mov     edx, [esi+8]
.text:00521057                 push    eax             ; int
.text:00521058                 mov     eax, [esi+4]
.text:0052105B                 push    ecx             ; int
.text:0052105C                 mov     ecx, [esi]
.text:0052105E                 push    ebx             ; int
.text:0052105F                 push    edi             ; int
.text:00521060                 push    edx             ; int
.text:00521061                 mov     edx, [esp+364h+var_31C]
.text:00521065                 push    eax             ; int
.text:00521066                 mov     eax, [esp+368h+var_318]
.text:0052106A                 push    ecx             ; int
.text:0052106B                 push    edx             ; int
.text:0052106C                 mov     edx, [esp+370h+var_338]
.text:00521070                 lea     ecx, [esp+370h+Str1]
.text:00521077                 push    eax             ; int
.text:00521078                 push    ecx             ; Str1
.text:00521079                 mov     ecx, [edx]
.text:0052107B                 push    5               ; int
.text:0052107D                 call    sub_54A510

Immediately after this routine completes, the text is drawn on the screen. The function has 11 arguments, the second one being the player name, and third being the RGB value of the player. For the purpose of developing this portion of the hack, the other arguments are irrelevant and probably relate to the position on the screen where the text is to be drawn if I had to take a guess. The idea then is to hook .text:0054A510, grab the stats for the players name, modify the resulting string (which will be in “%s: %d/%d” format) to our custom string, and then pass this back to the original function to be drawn on the screen. The resulting code would look like

__declspec(naked) int score_update_hook(int always_five, char *player, int rgb_value, int unk1, int unk2,
    int unk3, int unk4, int unk5, int unk6, int unk7, int unk8) {
    __asm pushad
    char *name; //Placeholder for address of name buffer
    __asm {
        mov ebx, dword ptr[esp+0x28]
        mov name, ebx
    }
    stats = items_find_by_name(&base_pointers, name);
    if(stats != NULL) {
        if(toggle_option == CURRENT_RES)
            _snprintf(name, SCORE_MAX_LENGTH, "W:%1.0f  F:%1.0f  G:%1.0f  S:%1.0f\0",
            stats->player_stat->wood, stats->player_stat->food, stats->player_stat->gold,
            stats->player_stat->stone);
        else if(toggle_option == ALL_RES)
            _snprintf(name, SCORE_MAX_LENGTH, "W:%1.0f  F:%1.0f  G:%1.0f  S:%1.0f\0",
            stats->player_stat->total_wood_gathered, stats->player_stat->total_food_gathered,
            stats->player_stat->total_gold_gathered, stats->player_stat->total_stone_gathered);
        else if(toggle_option == POP_AGE)
            _snprintf(name, SCORE_MAX_LENGTH, "Pop: %1.0f/%1.0f  Vil:%1.0f  Mil:%1.0f  Age:%1.0f\0",
            stats->player_stat->pop_current, (stats->player_stat->pop_current + stats->player_stat->pop_left),
            stats->player_stat->num_villagers, stats->player_stat->num_military, stats->player_stat->current_age);
    }
    __asm {
        popad
        jmp score_update
    }
}

The actual structure of the function is abused a bit here. Since .text:0054A510 has no local variables, we can create one on the stack at [EBP-0x4], since there won’t be anything to overwrite there. This dummy argument will act as our third argument at [ESP+0x28] (this function does not set up any sort of BP-based frame). Then anything we do to this dummy argument will be reflected as a change to the third parameter. Thus, the hook grabs the player name of who is to be updated, gets their stats, and checks what mode the user wants to be displayed. The modes are currently controlled through a regular enum in toggle_options.h

typedef enum TOGGLE_OPTIONS {
    CURRENT_RES = 1,
    ALL_RES,
    POP_AGE
} toggle_options;

Future plans can be to extend this system to allow the user to script their own format to be displayed with what they want. This technique still holds on multiplayer, as shown by the screenshots below.

Multiplayer note: The hooking technique posted below is detectable by Voobly. See the end of part 1 for suggestions on bypasses.

Usage: Enter a game and hit the hotkey to enable (default is F5). Use F6 to disable the hack, F7 to toggle options, and F8 to clear the stat list in case all names were not retrieved. A player is added to the list when they perform any action in game that modifies their resources. Duplicates are not stored in the list.

I’d prefer for the hack to develop through a series of articles instead of opening up a SVN server on here since that will give me motivation to continue its development.

The source for the in-game hack DLL can be found here.

A downloadable PDF of this post can be found here.

Categories: Game Hacking, Reverse Engineering Tags: