Jump to content


Most Liked Content


#25733 Basics of Assembler (Needed!)

Posted by Hagenees on 11 September 2009 - 03:49 PM

Hello guys,

Xain asked me to give him a website to learn ASM, And i knew i had it around somewhere well here is it the Basics all well explained and so damn clear!. Well enjoy and don't forget to REP+ :)

[DOWNLOAD LINK:]

Basics of Assembler.rar


#33808 L. Spiro Engine

Posted by L. Spiro on 23 July 2011 - 04:25 AM

Unsatisfied with my previous game engine, I have started a new one.
The new engine is a next-generation engine aimed at all platforms including iPhone and Nintendo Xii U, and PlayStation 4.  It will beat or meet CryEngine 3, and be available at a very low price to the public.

I have been working on it for 7 months, starting from scratch again.  I have made a completely new 3D file format, image format, etc., and all of the engine libraries are rewritten, including a new graphics engine.

This one is called L. Spiro Engine.  I am documenting my progress here: L. Spiro Engine
And forums can be found here: L. Spiro Engine Forums

I will be documenting my progress as I go, sharing helpful technical information about game engines, and providing sample downloads along the way.


So check out my new site, join the community, ask questions, and have fun!


L. Spiro


#31750 Signature scanning: a better solution

Posted by KEMiCZA on 19 October 2010 - 12:31 AM

dEViATED proud to present you a new tutorial. I'd suggest that you download and read it in notepad with terminal font. here's the introduction at least.

1.0) Introduction
     ------------
     One day I was working on a small trainer for Supreme Commander 2. Before I wanted to release it I saw an update had been
     released, and I didn't mind much and instantly applied the patch and made a new trainer for that version. A few days after
     the release another patch came out, and some people requested an update for the trainer. I thought to myself: well okay, I
     guess I can do it quickly. But this time I didn't bother using a memory searcher. I just used ollydbg to find a "sequence
     of commands", which I had from the previous update. And luckily it did find the address that matched with the assembly
     instructions. So I just changed the addresses in my source code (the caves were still the same), and the trainer would work.

     As you can guess a few days/weeks later another update came out, and I started thinking if I could come up with a method that
     could automatically search for the "sequence of commands", which were rather "sequence of bytes", just like ollydbg does. The
     only data necessary would be a sequence of a certain amount of bytes that relate to the assembly instructions at a location in
     games memory. I just thought of the idea, but I'm not even sure if I released a trainer for that particular patch. I started
     thinking about how I could implement it and maybe after a few weeks I got a basic template that could do exactly this. Over
     the time I've updated the engine a lot of times, fixed small bugs etc, but these were more related to the control of hotkeys
     and visuals than the actual scanning engine. After this, the method has been applied to other games by fellow dEViATED members
     and by myself with only positive feedback from trainer users.

     Infact I almost forgot to say that I have used this method before this game actually. And that was to patch the xlive memory
     checking. Since there were updates getting released for xlive, you couldn't guarantee that the address would always be the same.

     What you can expect from this tutorial is that I'll show you the basics and perhaps even some more advanced tips and
     technique's to help you on the way. I'll add some source code as well to help you understand.

Download the tutorial because it's not really readable on the forums.

Attached Files




#34456 Instant build trainer - Groza

Posted by Omega on 23 January 2012 - 03:02 PM

How to make instant build trainer Tutorial -- by Groza / May 2001

Target: Red Alert 2 version 1.004

I wrote this tutorial in order to show you how I made the instant build
option in my trainer for Red Alert 2. Because of a great demand I will
write how to make reveal map and skip mission options too.

WHAT WE NEED ?
--------------
- SoftIce ( the best tool, can't live without it )
- Winhack

To make an instant build trainer we have to find out the code that
cares(calculates) how long something will be building. There are many
possibilities how to find it out. I will explain just one of them, which
worked fine with me. Now if we think a little, there should be some parameter
in memory that is increasing or decreasing(depends on the game) during the
build. We are going to find it out.
So let's start building something. Now during building process we have to
find all the memory locations which are decreasing or increasing. First we
will try to find out those which are decreasing. In the game we start
building Barracks and as soon as it starts we pause the game(we press ESC),
ALT+TAB to WinHack choose the process of RedAlert 2(game.exe) and start
searching the locations. Then ALT+TAB back to the game, unpause and wait a
little. Back ALT+TAB to Winhack and use the -has decreased- option to search
only those memory locations which were decreased since the last search.
Then back to the game... we need to repeat doing this till we don't find only
one or few locations.
In Winhack we can also use other options like -has decreased by Less than %-
which can be very useful but I won't explain them here.

OK, everything should come well and we find the location(by me is 88FCEEC).
Let's check it out.

Back to the game and ALT+D to Softice. Be sure that we are in RA2(game.exe)
and not in some other process. Let's put a breakpoint on the address
bpmb 88FCEEC w and ALT+D to return to the game. SoftIce should pop up.

We should see something like this:

:004B9529   mov ecx, dword ptr [esi+68]
:004B952C   push edi
:004B952D   call 004E5470
:004B9532   mov eax, dword ptr [esi+5C]
:004B9535   mov [esi+58], 00
:004B9539   sub eax, edi                          <-this decrease our counter
:004B953B   mov dword ptr [esi+5C], eax
:004B953E   cmp dword ptr [esi+24], 00000036      <---interesting
:004B9542   jne 004B9574


Hm, let's patch it !!! Instead of sub eax, edi let's modify it by
sub eax,eax ! In this way we will decrease the counter so it should build
the thing instantly. Let's modify it, disable all breakpoints and back to
the game. What???#%&%#& Nothing happen. :(

But don't give up, let's check that cmp at the 004B953E. Seems it's comparing
the location pointed to [esi+24] with 36 hex. Let's check it out, disable
all breakpoints and put a bpmb [esi+24] w.

Back to the game and softice pop up here:

:004B94BF 8B4638                  mov eax, dword ptr [esi+38]
:004B94C2 8B5624                  mov edx, dword ptr [esi+24]
:004B94C5 03D0                    add edx, eax
:004B94C7 895624                  mov dword ptr [esi+24], edx
:004B94CA A15453A300              mov eax, dword ptr [00A35354]
:004B94CF 8B54240C                mov edx, dword ptr [esp+0C]

Hm, we can see that here is some other counter, which increases something.
And when it reaches 0x36 it is done. OK, let's modify the code in this
way then:

mov edx, 36
nop             //this 3 additional nops are because this instruction is
nop             //shorter than that we've replaced
nop
mov dword ptr [esi+24], edx

OK, disable all breakpoints and let's go back to the game. YES, IT WORKS !!!!
We have the instant build. Now we only need to make a trainer that will
modify the code when we press a button.
And that's all that has to be done. Easy isn't it ?



Please check the tutorial section on my page to find out more about
writing a trainer...

Greetz to MICRaL from TekZ 8193 for trying to make my page better !

From the heart of the winter,
Groza


#32076 Visual Basic Tutorial

Posted by FreckleS on 11 December 2010 - 12:25 AM

Hello, throughout this post I will teach you the basics of Visual Basic (.NET). Before we start I would like to clear up some things.
I am not saying that everything in this tutorial is 100% correct, if it was I would probably be getting paid millions. I also would like to point out that this has no benefit to me, I know the language, you don't so if you find something that is wrong or isn't explained well don't get grumpy and rage at me, ask me to clarify it for you and I will do my best.
This is only a beginners tutorial, you should not assume total knowledge of Visual Basic after reading this, it will give you enough information to be able to develop "decent" software whilst you continue to broaden your knowledge.

Who am I?
I am FreckleS. I have been developing software in Visual Basic for over 4 years and other languages like C/C++ for 3.
This tutorial may only be posted on my chosen sites which are listed in credits, it may be linked to with credits to me. If you wish to post this on another site, ask me and chances are I will let you.

There might well be a few details here and there and spelling mistakes etc wrong so please if I have made mistakes please pm me them and don't fill the thread with them, I will fix them asap.

First off I am not going to show you how to install VB and create a new project and all that crap as you should be able to that before you start this tutorial.

I will use Console Applications as it saves me a lot of time creating Forms and taking screenshots for you and all that crap.

Lesson 1 - Good Ol' Hello World
The code that most programmers start with, Hello World. The Hello World program is one of the most basic programs that can be created in any language. Even though it is extremely simple it still has a few key parts to it.
' Lesson1 - Hello World
Module Lesson1
    Sub Main()
        Console.WriteLine("Hello World")
        Console.ReadLine()
    End Sub
End Module
On the first line you see:
'Lesson1 - Hello World
This is a comment, any text that follows a "'" is considered to be a comment. The compiler will ignore this line.

Comments are one of the most useful types of internal documentation that can be included in a program. Although in this example it would probably be not needed it is good to start good programming practices from your very first application.

Line 3 is one of the most important parts of the program.
    Sub Main()
Tells the compiler that this is the main function or sub routine. Every Visual Basic Console Application will have this function by default, or you can set the startup function to be something else, I suggest not doing this at least until you are more comfortable with the language as it is not overly needed.

Line 4 is what makes your program actually "talk"
        Console.WriteLine("Hello World")
This does exactly what you think it does. It writes the text "Hello World" to the Console Window.

WriteLine and many other functions are member functions of the Class "Console". The Console Class has many properties which can be set through the say way as you just wrote a line to the console, Class.Function or Class.Property = whatever.

Line 5 is just a line of code that makes a program pause and wait for the user to hit a key before exiting so that we can read the output.
        Console.ReadLine()
Again you see the use of the Console Class. You will soon become more familiar with ReadLine function as it is often used to give variables values etc.

Line 6 you tell the compiler that it is the end of your sub routine.

Lesson 2 - Variables
Just like in math and algebra something that changes its value is called a variable, the same rule applies in programming.

Variables are a key part of a program for any language and the same applies for Visual Basic. A variables value can be changed with the Assignment Operator (=), you will learn more about this in the coming lessons.

A variable must have a name and data type before it can be used, this is called declaring. In Visual Basic you can declare variables by the following syntax.
Dim <name> As <type>
So if I wanted to declare a variable to hold my age I would declare it like this
Dim myAge As Integer
This tells the compiler to set aside memory to hold an Integer (4 bytes usually) for the variable myAge.

Now that the variable has been declared we can set its value, get its value and use it for many other purposes.

Remember the Assignment Operator (=)?
Visual Basic is a language that has the same operator for testing equality and assigning values.
Example.
myAge = 15
Is a good use of the Assignment Operator
If myAge = 15 Then
Is a good use of the Equality Operator to test a value.

Not only can you set the value of a variable you can get it and use it.
' Lesson 2 - Variables
Module Lesson2
    Sub Main()
        Dim myAge As Integer ' Declare myAge variable as type Integer
        myAge = 15 ' Assign myAge with 15
        Console.WriteLine("I am {0} years old", myAge) ' Write myAge to the screen
        Console.ReadLine() ' Wait for key press
    End Sub
End Module
Line 6 is a demonstration on how to write a variables value to the console window. you might think "what the hell is {0}" this tells the compiler that console.writeline will take 2 arguments now, not just the message but it will take an object in an argument. It also says take the value of the object and place it here.

Another way of writing this would be to join the values.
        Console.WriteLine("I am " & myAge & " years old") ' Write myAge to the screen
This looks messier although neither has a real benefit over the other it is just preference and neater code. All of which comes back to easier manageable code which in turn makes for better code.

The main datatypes are the following:

    * Integer
    * Single
    * Double
    * Boolean
    * String
    * Byte
    * Char
    * Decimal



For an understanding of the datatypes read http://www.rentron.com/datatypes.htm

Quick Note - Understanding Operators
There are a few types of operators available to Visual Basic, as well as other languages, that make our lives easier. These include, mathematical, relational, logical and assignment operators.

In Visual Basic unlike a few other languages it has the same Assignment Operator and the same Equality Operator which is a member of the Relational Operator family. They are both (=). I personally am not sure if I like this prefered to a language like C++ where the equality operator is (==).

Relational Operators:
Here is a quick list of the relational operators:
Name, Operator, Sample, Evaluates
Equals, =, 10 = 20, False
Not Equals, <>, 10 <> 20, True
Greater Than, >, 10 > 20, False
Less Than, <, 10 < 20, True
Greater Than or Equal to, >=, 10 >= 20, False
Less Than or Equal to, <=, 10 <= 20, True

Logical Operators:
And, Or, Not, AndAlso, Xor, OrElse
They work in the way in which you might expect.

And:
It is used to evaluate two expressions. If both are correct then it will return true if not it will return false.

Or:
It is used to evaluate two expressions. If either one is correct then it will return true, if neither are correct it will return false.

Not:
It is used to evaluate an expression. If the expression evaluates to false then it will return true. It is has much or less the same effect as <>.

Mathematical Operators:
Like you would expect in maths, plus (+), minus (-), multiplication (*), division (/) and modulus (Mod)

You should be fairly comfortable with the mathematical operators except for perhaps modulus. A good example of the modulus operator would be to find if a number was even or not. Modulus returns the remainder of a division.
So 10 Mod 2 = 0 because it is evenly divisible.
Module Module1
    Sub Main()
        Console.WriteLine("Enter Number: ")
        Dim num As Integer
        num = Console.ReadLine
        If num Mod 2 = 0 Then
            Console.WriteLine("Even!")
        Else
            Console.WriteLine("Odd!")
        End If
        Console.ReadLine()
    End Sub
End Module
You can review more about operators here:
http://www.startvbdo.../operators.aspx

Lesson 3 - If/Else Statements
The 3 Control Structures for any program as my software teacher keeps reminding me is Sequence, Selection and Repition.

If/Else Statements fall into the Selection catagory of these structures. It is just like it sounds, it will select which path to take. Code will always follow Sequence, it is a control structure that will always be, code will always flow, one statement after the other.
In some cases it will take a different path (selection) or it might go over the same path again (repeition).

Obviously you can't always know what a user is going to enter into your program so you need to be able to handle this, if you don't you program will most likely crash or something else bad will happen. If/Else Statements are a great way of handling exceptions and keeping your program bug free. The only better way of handling exceptions would be Try/Catch Statement but we will look into that later.

The Syntax for a If/Else Statement is.
If <Expression> Then
<Statements>
Else
<Statements>
End If
We used a very basic If Statement in the last lesson, although the code was unfinished it should have given you an overview of the statement.
' Lesson 3 - If/Else Statements
Module Lesson3
    Sub Main()
        Dim myAge As Integer ' Declare myAge variable as type Integer
        myAge = 15 ' Assign myAge with 15
        If myAge = 15 Then ' Is myAge variable equal to 15?
            ' Yes
            Console.WriteLine("I am {0} years old", myAge) ' Write myAge to the screen
        Else
            ' No
            Console.WriteLine("I am not {0} years old", myAge) ' Write error to the screen
        End If ' Close if/else statement

        Console.ReadLine() ' Wait for key press
    End Sub
End Module
Obviously this will write the message "I am 15 years old" because you have assigned the variable myAge to be 15. This is just a basic example of the statement. Next we will look at user input to help make this and other programs a bit more functional.

Lesson 4 - User Input
In most of your applications you are going to need user input to select something, change a setting or whatever. You can achieve this by using the Console Class again as we have been using all the way through this tutorial.

We can use almost the exact same program from Lesson 3 or even Lesson 2 only with a minor change.
When we assign the value of myAge we are not going to give it a value, but more we are going to give it a function to run which will return a value and assign it to myAge variable. The definition of the ReadLine function is:

Public Shared Function ReadLine() As String
     Member of System.Console
Summary:
Reads the next line of characters from the standard input stream.

Return Values:
The next line of characters from the input stream, or null if no more lines are available.

Exceptions:
System.IO.IOException: An I/O error occurred.
System.OutOfMemoryException: There is insufficient memory to allocate a buffer for the returned string.
System.ArgumentOutOfRangeException: The number of characters in the next line of characters is greater than System.Int32.MaxValue.
Basically all that that says is that it calls the member function ReadLine of class Console (System.Console to be 100%) and then returns the next line of character entered.

Our assignment of myAge should now look like.
myAge = Console.ReadLine()
That been said you should be able to implement it into your previous programs, I will do it with Lesson 3 so that we can use If/Else statements and also it is good to practice as you will learn from doing.

You should also print a message before recieving input, something like "Please enter my age: " or something like that. You can do this by the member function WriteLine of class Console (You should remember).

' Lesson 4 - User Input
Module Lesson4
    Sub Main()
        Dim myAge As Integer ' Declare myAge variable as type Integer
        Console.WriteLine("Please enter my age: ")
        myAge = Console.ReadLine() ' Assign myAge with user input
        If myAge = 15 Then ' Is myAge variable equal to 15?
            ' Yes
            Console.WriteLine("I am {0} years old", myAge) ' Write myAge to the screen
        Else
            ' No
            Console.WriteLine("I am not {0} years old", myAge) ' Write error to the screen
        End If ' Close if/else statement

        Console.ReadLine() ' Wait for key press
    End Sub
End Module
Lesson 5 - Functions/Sub Routines
This and the next lesson, Variable Scope, go hand in hand with each other. Throughout these tutorials I am going to refer to Sub Routines and Functions as the same thing, which they basically are, I do this because of my obession with C++ and other languages (foolish me...)

The really only difference is that a function returns a value, there are a couple of minor differences but nothing you need to worry about in these tutorials. Oh and of course the other difference. The keywords are different.

Keywords are words that are set aside by the compiler to be "special". You can't use these words in declarations etc, you can't name an integer variable like.
Dim integer As Integer
Anyway...

Functions are the building blocks of programs, commercial software will have a huge number of functions in it. Functions allow you to split your program into parts which makes your program much easier to maintain for other programmers who might come into contact with your code.

In Visual Basic unlike in other languages like C++ you don't need a function prototype before using your function. You can declare the function by using the following syntax.
Function <Name>(Arguments) As <Type>
<Statements>
Return <Value>
End Function
You should always take care when naming your functions. A function should only do one task and it should be named according to that task.

An example is the Doubler function. It takes a number as an argument then it returns the value twice the number passed to it.

' Lesson 5 - Functions/Sub Routines
Module Lesson5
    Sub Main()
        Console.WriteLine(Doubler(5)) ' Display the double of 5
        Console.ReadLine() ' Wait for user input
    End Sub

    Function Doubler(ByVal num As Integer) As Integer
        Return num * 2 ' Return the entered number times by 2
    End Function
End Module
To call a function you don't need to write the value to the screen, you can just call it like so.
<Name>(<arguments>)
A sub routine can be used in much the same way except you change Function to Sub.

Lesson 6 - Variable Scope
Variable Scope is an important part for variables, especially when you start using multiple functions. Variable Scope is a problem that many new programmers come into contact with. I often see on forums people posting a compile error like <Variable> is not declared, even when it is. This is because the function that they are trying to access the variable from doesn't have permissions.
This means that if you declare a variable within another function it will not be accessable in others. Try this program and you will understand.
' Lesson  6 - Variable Scope
Module Lesson6
    Sub Main()
        Dim myAge As Integer
        myAge = 15
    End Sub

    Function DoubleAge()
        Return myAge * 2 ' DoubleAge function doesn't know of myAge variable
    End Function
End Module
You should recieve the following error.
Error 1 Name 'myAge' is not declared. C:\Documents and Settings\FreckleS\Local Settings\Application Data\Temporary Projects\Lesson6\Module1.vb 9 16 Lesson6

This is because the variable is declared with the function Main(). In order to use the variable in DoubleAge() function you would need to pass it as a argument or parameter or you can declare the function outside of any other function which makes it available to any function. I will demonstrate both options.

' Lesson  6 - Variable Scope
Module Lesson6
    Dim myAge As Integer
    Sub Main()
        myAge = 15
        Console.WriteLine(DoubleAge)
        Console.ReadLine()
    End Sub

    Function DoubleAge()
        Return myAge * 2 ' DoubleAge function doesn't know of myAge variable
    End Function
End Module
and

' Lesson  6 - Variable Scope
Module Lesson6
    Sub Main()
        Dim myAge As Integer
        myAge = 15
        Console.WriteLine(DoubleAge(myAge)) ' Pass myAge to DoubleAge function.
        Console.ReadLine()
    End Sub

    Function DoubleAge(ByVal num As Integer)
        Return num * 2 ' DoubleAge function doesn't know of myAge variable
    End Function
End Module
In the second example DoubleAge still doesn't know about myAge, all it knows is that its value (15) is passed to it as the num argument.

Lesson 7 - Select Case Statements
Remember the 3 control structures, Sequence, Selection, Repetition? Well these is If/Else statement's big brother. He can handle multiple selections with ease, much like if/else if/else. Although this can become cubersome with a large amount of selections, select case however...never

The syntax for a Select Case Statement
Select Case <Expression>
    Case <Expression>
        <Statement>
    Case Else
        <Statement>
End Select
In my example I am just lazy so I didn't do all the options but you get the idea.
' Lesson 7 - Select Case Statements
Module Lesson7
    Sub Main()
        Dim myAge As Integer
        Console.WriteLine("Please enter my age: ")
        myAge = Console.ReadLine()
        Select Case myAge
            Case 1
                Console.WriteLine("Im not 1")
            Case 2
                Console.WriteLine("Im not 2")
            Case 3
                Console.WriteLine("Im not 3")
            Case 15
                Console.WriteLine("I am 15!")
            Case Else
                Console.WriteLine("I handle exceptions like you!")
        End Select
        Console.ReadLine()
    End Sub
End Module
On Line 7 it sets up the statement. This would be the same as writing
' Lesson 7 - Select Case Statements
Module Lesson7
    Sub Main()
        Dim myAge As Integer
        Console.WriteLine("Please enter my age: ")
        myAge = Console.ReadLine()
        If myAge = 1 Then
            Console.WriteLine("Im not 1")
        ElseIf myAge = 2 Then
            Console.WriteLine("Im not 2")
        ElseIf myAge = 3 Then
            Console.WriteLine("Im not 3")
        ElseIf myAge = 15 Then
            Console.WriteLine("I am 15!")
        Else
            Console.WriteLine("I handle exceptions like you!")
        End If
        Console.ReadLine()
    End Sub
End Module
Even whilst I was writing that, small amount of selection I got bored with the if/else statements much before the select case statements.

Lesson 8 - Arrays
Arrays are a wonderful, powerful and mighty feature of Visual Basic. They allow you to store related information within the "same" variable.
They are declared almost the same as a variable except that after the name you place brackets and the number of elements it can hold. In Visual Basic arrays are "Zero Based" which means the index starts at 0 so:
        Dim customerNames(4) As String
Creates an array which can hold 5 elements(0, 1, 2, 3 and 4).

To assign an individual array you once again use almost the same syntax as for a variable.
        customerNames(0) = "John Reed"
        customerNames(1) = "Jack Smith"
        customerNames(2) = "Ella Harper"
        customerNames(3) = "Max Johnson"
        customerNames(4) = "Samantha Pong"
The following code is quite cubersome and you will learn how to improve on this method shortly.
' Lesson 8 - Arrays
Module Lesson8
    Sub Main()
        Dim customerNames(4) As String
        customerNames(0) = "John Reed"
        customerNames(1) = "Jack Smith"
        customerNames(2) = "Ella Harper"
        customerNames(3) = "Max Johnson"
        customerNames(4) = "Samantha Pong"

        Console.WriteLine(customerNames(0))
        Console.WriteLine(customerNames(1))
        Console.WriteLine(customerNames(2))
        Console.WriteLine(customerNames(3))
        Console.WriteLine(customerNames(4))

        Console.ReadLine() ' Wait for user input to exit.
    End Sub
End Module
Lesson 9 - Recursion & Loops
The final control structure, Repetition.

Repetition is a great feature of any programming language, it allows for things to do be done, a set number of times or an infinite number of times, however you should try to avoid this as it generally strains the CPU.

There a few different types of loops.

    * Do...Until
    * Do...While
    * For Each...Next
    * Do...Loop



Also in functions you can call the function from the same function which is called Recursion.

A very basic loop is one that counts to 10.

First you will need to declare a variable called "counter" as an integer.

We will use either a Do Until or a Do While Loop, they achieve the same thing but have a slight difference in the expression.

The syntax for a loop is generally.
[code[
Do Until <Expression>
<Statements>
Loop
[/code]

We will use a counter integer as the test expression. This basically sets our number of loops.

' Lesson 9 - Recursion & Loops
Module Lesson9
    Sub Main()
        Dim counter As Integer = 1 ' Declare counter variable as Integer and assign 1 to it.
        Do Until counter = 11 ' Loop until counter equals 11
            Console.WriteLine(counter) ' Print the current value of counter
            counter += 1 ' Increment counter
        Loop ' Go again
        Console.ReadLine() ' Wait for user input to exit.
    End Sub
End Module
This should give the output.
1
2
3
4
5
6
7
8
9
10

Wonderful...Why doesn't it print out 11 though you ask. Well...The loop tells us.
Do Until counter = 11
Until is the keyword there. Once it is equal to 11 it will not loop again and go to the next line of code after the loop.

Similiarly. Do While loops work in much the same manner.

' Lesson 9 - Recursion & Loops
Module Lesson9
    Sub Main()
        Dim counter As Integer = 1 ' Declare counter variable as Integer and assign 1 to it.
        Do While counter <> 11 ' Loop until counter equals 11
            Console.WriteLine(counter) ' Print the current value of counter
            counter += 1 ' Increment counter
        Loop ' Go again
        Console.ReadLine() ' Wait for user input to exit.
    End Sub
End Module
That strange operator you see there "<>" is the not equals operator, or the Inequality Operator. Then you also all your normal maths crap, > greater than, < less than, >= greater than or equals to, <= less that or equals to.

For Each...Next Loops as a wonderful loop that can be used to loop through something for a finite amount of times. Using an array is the perfect example so from the previous lesson.
' Lesson 9 - Recursion & Loops
Module Lesson9
    Sub Main()
        Dim customerNames(4) As String
        customerNames(0) = "John Reed"
        customerNames(1) = "Jack Smith"
        customerNames(2) = "Ella Harper"
        customerNames(3) = "Max Johnson"
        customerNames(4) = "Samantha Pong"

        For Each name As String In customerNames
            Console.WriteLine(name)
        Next

        Console.ReadLine() ' Wait for user input to exit.
    End Sub
End Module
Lesson 10 - Classes
Classes are the building blocks to Object Orientated Programming (OOP). OOP is one of the main benefits of languages like Visual Basic and C++ over C and other languages. C is a structured language. OOP allows you to think about real world objects as if they were part of your computer. The world is filled with objects, cars, cats, dogs, trees, houses etc. These objects have characteristics, tall, brown, small, bark.

OOP allows you to "import" these objects into your computer to manipulate. If you are looking for more information on OOP look up some C++ stuff. C++ was designed a bridge between C and OOP to bring the power of OOP to the commercial developer platform of C so there is plenty of resources about.

Declaring a class is much like declaring a function or even a variable. It can also contain both of these.

The syntax for declaring a class is.
Class <Name>
<Variables>
<Functions>
End Class

I am going to use a Cat as an example.
    Class Cat
        ' Declare variables
        Public itsAge As Integer = 3
        Public itsWeight As Integer = 20

        ' Create meow function
        Sub Meow()
            Console.WriteLine("Meooowww")
        End Sub
    End Class
That is your class declared but now we want to use it. We need to create an object to be able to use it. In Main or whatever function you are in you can declare your object like so.
Dim <Object> As New Cat
Dim Jasper As New Cat ' Create a new object instance of Cat named Jasper
Now you have a "working" Cat. To use the cat you can simply use the Object name followed by a period (.) then the member variable or member function or whatever.

' Lesson 10 - Classes
Module Lesson10
    Class Cat
        ' Declare variables
        Public itsAge As Integer = 3
        Public itsWeight As Integer = 20

        ' Create meow function
        Sub Meow()
            Console.WriteLine("Meooowww")
        End Sub
    End Class

    Sub Main()
        Dim Jasper As New Cat ' Create a new object instance of Cat named Jasper
        Console.WriteLine("Jasper weighs {0} and is {0} years old", Jasper.itsWeight, Jasper.itsAge) ' Get member variable info from the class
        Jasper.Meow() ' Make jasper meow.
        Console.ReadLine()
    End Sub
End Module
Believe it or not but you have been using OOP code since you started with that very first application, Hello World. When I mentioned member function of class with Console.ReadLine that is the exact same as this.
Ours:
Class = Cat
Member Function = Meow

Systems:
Class = Console
Member Function = ReadLine

Amazing isn't it?

Lesson 11 - File Manipulation
File Manipulation is a very important part of programming, for me anyway. I like to often read values from text files and store data in them if I don't want to use registry or settings (don't worry).

This Lesson is sort of a challenge. It will be short and sweet and as it is really a combination of some of the previous lessons hopefully you will be able to pick it up really easy.
We need to import System.IO however which you may not have done before. This allows us to use code from the System.IO file. At the top of your workspace simply type.
Imports System.IO
Now we can use may features from the System.IO dll. One of which is StreamReader and its brother StreamWriter. You guessed it, this allows us to read and write bytes with a certain encryption to a file of our choice.

You need to create an object of the StreamReader class and then we need to read the file so check out the member function ReadToEnd(). The code I came up with is.
' Lesson 11 - File Manipulation
Imports System.IO ' We use this file to input/output files.
Module Lesson11
    Sub Main()
        Console.WriteLine(ReadFile("C:\Testfile.txt"))
        WriteFile("C:\TestFile2.txt", "Hello there GREAT VB Coder!")
        Console.ReadLine()
    End Sub

    Function ReadFile(ByVal targetFile As String)
        Dim fileContents As String ' Declare variable
        Dim read As New StreamReader(targetFile) ' Create a new object of the Class StreamReader
        fileContents = read.ReadToEnd ' Assign the variable to the return value of the member function
        read.Close()
        Return fileContents ' Return the contents of the text file using a member function from StreamReader class
    End Function

    Function WriteFile(ByVal targetFile As String, ByVal text As String)
        Dim write As New StreamWriter(targetFile) ' Create a new object of the Class StreamWriter
        write.WriteLine(text)
        write.Close()
    End Function
End Module
Hopefully you got something very similiar if not better and hopefully you got it easily. A couple of attempts and you should have it perfect. Make sure that you close the file or you will get errors next time you try to use it.

Lesson 12 - Try Catch Statements
I somewhat forgot about this but its ok cause its back now. It wasn't really needed too bad previously but it would have done good in the previous example.

The Try...Catch Statement is used catch exceptions that may occur whilst you are trying to do something. Usually something with a high chance of failing.

If I was to use the same sort of thing on the previous example it would like this.
' Lesson 12 - Try Catch Statements
Imports System.IO
Module Lesson12

    Sub Main()
        Try
            Console.WriteLine(ReadFile("C:\Testfile.txt"))
            WriteFile("C:\TestFile2.txt", "Hello there GREAT VB Coder!")
            Console.ReadLine()
        Catch ex As Exception ' Stops crashing
            Console.WriteLine(ex) ' Display exception
            Console.ReadLine()
        End Try
    End Sub

    Function ReadFile(ByVal targetFile As String)
        Dim fileContents As String ' Declare variable
        Dim read As New StreamReader(targetFile) ' Create a new object of the Class StreamReader
        fileContents = read.ReadToEnd ' Assign the variable to the return value of the member function
        read.Close()
        Return fileContents ' Return the contents of the text file using a member function from StreamReader class
    End Function

    Function WriteFile(ByVal targetFile As String, ByVal text As String)
        Dim write As New StreamWriter(targetFile) ' Create a new object of the Class StreamWriter
        write.WriteLine(text)
        write.Close()
    End Function
End Module
Delete the file "C:\Testfile.txt" and see what happens. You get this ugly long exception message. Since this is one of the most likely exceptions that occur we can count on that and make the handling a bit smoother, more user friendly.

' Lesson 12 - Try Catch Statements
Imports System.IO
Module Lesson12

    Sub Main()
        Try
            Console.WriteLine(ReadFile("C:\Testfile.txt"))
            WriteFile("C:\TestFile2.txt", "Hello there GREAT VB Coder!")
            Console.ReadLine()
        Catch ex As FileNotFoundException ' Stops crashing when file isn't found
            Console.WriteLine("File not found!") ' Display exception
            Console.ReadLine()
        End Try
    End Sub

    Function ReadFile(ByVal targetFile As String)
        Dim fileContents As String ' Declare variable
        Dim read As New StreamReader(targetFile) ' Create a new object of the Class StreamReader
        fileContents = read.ReadToEnd ' Assign the variable to the return value of the member function
        read.Close()
        Return fileContents ' Return the contents of the text file using a member function from StreamReader class
    End Function

    Function WriteFile(ByVal targetFile As String, ByVal text As String)
        Dim write As New StreamWriter(targetFile) ' Create a new object of the Class StreamWriter
        write.WriteLine(text)
        write.Close()
    End Function
End Module
Lesson 13 - Data Type Conversion
Sometimes you might need data as a specific data type. Somebody might try to be smart and enter a double when you ask for an integer or something like that.

In Visual Basic there are two types of Data Type Conversion, Implicity and Explicity. Implicity means that you do the conversion yourself. You don't actually convert but you store a value as the "wrong" data type and it will lose data.
An example.
' Lesson 13 - Data Type Conversion
Module Lesson13
    Sub Main()
        Dim doub As Double = 15.723
        Dim int As Integer
        int = doub ' Integer is a whole number
        Console.WriteLine(int)
        Console.ReadLine()
    End Sub
End Module
Since an Integer data type is a whole number the output will be 16. The compiler will round doub up.

Explicity means that the data will automatically be converted.
Visual Basic comes with a class called CType. It is a cast and the above example would like this this.
' Lesson 13 - Data Type Conversion
Module Lesson13
    Sub Main()
        Dim doub As Double = 15.723
        Dim int As Integer
        int = CType(doub, Integer) ' Convert to integer
        Console.WriteLine(int)
        Console.ReadLine()
    End Sub
End Module
Or we could also use CInt which is the cast type of int.
' Lesson 13 - Data Type Conversion
Module Lesson13
    Sub Main()
        Dim doub As Double = 15.723
        Dim int As Integer
        int = CInt(doub)
        Console.WriteLine(int)
        Console.ReadLine()
    End Sub
End Module
Other data type conversion functions in Visual Basic include:
Function, Use
CBool, Convert to Boolean Data Type
CByte, Convert to Byte Data Type
CDate, Convert to Date Data Type
CSng, Convert to Single Data Type
CShort, Convert to Short Data Type
CInt, Convert to Integer Data Type
CLng, Convert to Long Data Type
CDbl, Convert to Double Data Type
CDec, Convert to Decimal Data Type
CObj, Convert to Object Data Type
CString, Convert to String Data Type
CChar, Convert to Char Data Type

Lesson 14 - Enumeration
Enumeration is the use of a related set of constants, it is similiar to Classes but not quite as cool. The problem with enumeration is that you are working with constants, this is of course good in some instances but I prefer to work with classes, do as you wish. Fine...Ill teach you both.

You can declare an enumerated type with the following syntax.
Enum <Name>
<Constants>
End Enum
Then the same as classes you can reference your constants with the Enum name followed by a period (.) then the constant.

' Lesson 14 - Enumeration
Module Lesson14
    Enum Colours
        red = 1
        green = 2
        blue = 3
    End Enum
    Sub Main()
        Console.WriteLine("Red is the number " & Colours.red & " colour")
        Console.ReadLine()
    End Sub
End Module
Lesson 15 - Multithreading
Multithreading is one of the most important parts of software developement. For me anyway. A lot of software is going to need to be able to do several things at once or a couple of high CPU or time consuming tasks at the same time. If your application is running on a single thread and you want to do a couple of these tasks at once then your program will lag.

I will use the example of downloading a file from my website. First you must import the .dll System.Threading. So at the very top of your page:
Import System.Threading
You also must create a new function that will contain your code to download the file, or whatever it is you are making.

Now as you should know by now, we can now use its member functions of the System.Threading Class. But as again you should know by now we have to create an object instance of it so we can use it.
    Dim myThread As New Thread(AddressOf DownloadFile)
A member function of the Thread class is Start. What do you think that does? Use it when you want to use your function.

' Lesson 15 - Multithreading
Imports System.Threading
Module Lesson15
    Dim myThread As New Thread(AddressOf DownloadFile)
    Sub Main()
        Console.WriteLine("Single thread.")
        myThread.Start() ' Start the new thread
        Console.WriteLine("Don't have to wait for it to finish!")
        Console.ReadLine()
    End Sub

    Function DownloadFile()
        Try
            My.Computer.Network.DownloadFile("http://gamesalter.com/freckles/coding/Banned.exe", "C:\lol.exe")
            Console.WriteLine("Finished download!")
            myThread.Abort() ' Cancel the thread to avoid excess CPU usage.
        Catch ex As Exception
            Console.WriteLine(ex)
        End Try
    End Function
End Module
You should also remember to use the member function Abort() when you are finished with your thread as it will give the CPU a break.

A couple more member functions of the Thread Class include:

    * Sleep
    * Resume
    * Suspend



You can also set the priority of threads just like you can to processes in Task Manager.

Priority = ThreadPriority.Highest

The list of priorities include:

    * Lowest
    * Below Normal
    * Normal
    * Above Normal
    * Highest



I think your done. Now here is some useful code snippets that you can use just give credits to me.

Custom CopyFile Class
Imports System.IO

Module CopyFileClass

    Sub Main()
        Console.Title = "Custom CopyFile Class"

        Dim strSrcFile, strDestFile As String
        Console.WriteLine("Please Enter Source File: ")
        strSrcFile = Console.ReadLine()

        Console.WriteLine("Please Enter Destination File: ")
        strDestFile = Console.ReadLine()

        CopyFile(strSrcFile, strDestFile)
    End Sub

    Sub CopyFile(ByVal SrcFile As String, ByVal DestFile As String)
        Try
            File.WriteAllBytes(DestFile, File.ReadAllBytes(SrcFile))
        Catch ex As Exception
            Console.WriteLine(ex.Message)
            Console.ReadLine()
            Exit Sub
        End Try
        Console.WriteLine(vbCrLf & "Successfully Copied {0} To {1}", SrcFile, DestFile)
        Console.ReadLine()
    End Sub
End Module
Recursive File Search
Imports System.IO
Module Module1
    Sub Main()
        Search("C:\") ' Which directories to search
        Console.ReadLine() ' Display Output
    End Sub

    Sub Search(ByVal directoryPath)
        Dim files() As String ' Unset array of files
        Dim directories() As String ' Unset array of directories

        files = Directory.GetFiles(directoryPath) ' Load all files
        For Each File In files ' Each file
            Console.WriteLine(File)
        Next ' Get the next file

        directories = Directory.GetDirectories(directoryPath) ' Load all the sub directories
        For Each Directory In directories ' Each directory/sub directory
            Console.WriteLine(Directory) ' This will write the directory (not needed but you can use)
            Search(Directory) ' Go again in new directory
        Next ' Get the next directory
    End Sub
End Module
Basic Anti-Leak Protection
Imports System.Management

Module AntiLeak
    Sub Main()
        ALP()
    End Sub

    Friend Function GetVolumeSerial(Optional ByVal strDriveLetter As String = "C") As String
        Dim hds As ManagementObject = New ManagementObject(String.Format("win32_logicaldisk.deviceid=""{0}:""", strDriveLetter))
        hds.Get()
        Return hds("VolumeSerialNumber").ToString()
    End Function

    Private Sub ALP()
        Select Case (GetVolumeSerial())
            Case Is = "58057611"
                MessageBox.Show("Anti-Leak Protection Passed" & vbCrLf & "Welcome Jarrad Freck - Creator", "Success")
            Case Is = "F85A4208"
                MessageBox.Show("Anti-Leak Protection Passed" & vbCrLf & "Welcome Jean Doe - Customer", "Success")
            Case Is = "C457CD21"
                MessageBox.Show("Anti-Leak Protection Passed" & vbCrLf & "Welcome John Smith - Beta Tester", "Success")
            Case Else
                MessageBox.Show("Anti-Leak Protection Failed", "Failed")
                Application.Exit()
        End Select
    End Sub
End Module
Yeah thats enough code, you can also learn a bit by studying these codes.

By reading ALL of this doesn't make you a Visual Basic programmer, it gives you a good step into the language however. There are thousands of resources out there and in time you will become better and better just keep practicing and coding. The best way to learn is by doing.

Credits:

    * FreckleS
    * reddy <3
    * ProjectGhostt.com

This tutorial may not be distributed without my permission, ask me if you would like to and chances are I will let you. Do the right thing by me and I will return the favour.

If people find that I have done something wrong please let me know, I am not perfect and this has really taken it out of me. I know that I haven't explained everything perfectly and if you would clarification ask. Or contact me at:
Email: projectghostt@gmail.com
Web: http://projectghostt.com
MSN: freckles@muppetalert.com
Xfire: freckles123
Steam: Code_Ducks
PM: At any of the above listed sites.

Have fun!


#35650 Noobs Code Injection When and How Tutorial

Posted by demetron on 22 October 2012 - 01:25 PM

Code Injection When And How Tutorial By DEMETRON

http://www.gamehacki...24788-demetron/

Target : Command & Conquer Red Alert 3
Version : 1, 0, 0, 0
Aim : Hacking money via code injection so only your money won’t decrease but your opponent’s will.
Level of Difficulty: Novice(beginners level)
Tools Required:  
-The game off course
-Cheat Engine (I am using version 5.5)
-Notepad++ or any other text editor to note addresses and other stuffs.
Pre-Requisites:
-None but some knowledge of assembly and experience of cheat engine is a plus.(if you don’t it’s ok!)
Note:  This tut. assumes that you were born yesterday and had no prior knowledge of game hacking  so you can skip some parts according  to your knowledge.

Part 1 : Finding Addresses

Let’s start with finding addresses which store our money value. to do this start cheat engine now if we open our game it will be opened in full screen mode and that sometimes create trouble when attaching debugger to it, so let’s open the game in a window. If you go to game option and search there is already  a check box to run the game in a window mode we can use that other way to do this is go to the shortcut of the game right click on it, go to properties and in the target add -win after a space so your target will become something like "C:\Program Files\Red Alert 3\RA3.exe" –win  now open your game and it’ll run in window like given screen shot.
Posted Image

Now with your game running go to cheat engine click on process (in menu bar) and you’ll see lots of process in this list (it’s basically every process running in the system right now) but we have to find the process of our game and that’s pretty easy actually on top (not necessarily ) you will see the two processes having the logo of our game yup those two processes are related to our game but which one to select now, In general the process with *.EXE are shown only but in this case you we’ll see a *.game extension also and we are going to select that one for debugging because that’s the main module which contains the address not the other one(you are welcome to gamehacking.com) to understand this phenomena completely. So select one with the *.game extension in it.

Posted Image

Ok our platform is set now we can do some serious things just go to game’s skirmish option and start a game with no opponents(why? Because we don’t want our base is to be destructed when we are in middle of a search) and just because you are curious :D I choose Allied Nations, blue color,battlebase beta map(1’st on the list) initial resource 25000 and no random crates. Let’s begin to play and before doing anything go to cheat engine again and check the pause the game while scanning option it will ask you to attach debugger to game click yes. Now in the cheat engine’s value option enter 25000(as mine is 25k at starting and if yours is different enter whatever amount you have)
Posted Image

Leave all other settings to default and press First Scan and I got 121 results(addresses) you might get more or less doesn’t matter at this point.Ok now we go back to game again build  a power plant it’ll cost $800 (you can build anything else if you want we are just spending some money here) and now I have $24200 remain on my account so let’s put this value in cheat engine and press next scan and wow we just got 3 results now J now spend some more money or earn some money back by selling things and do the same search again until you get the final results (yup those 3 address are the final results)and as it’s just 3 results we can check them manually now select all address and press the arrow button in bottom which says copy all selected items to address list or you can just double click on each 3 addresses to add them to list below. Now at the table there are fields like address|type|value click on value of each 3 address we just add and try to modify it, And hopefully one address is the address we are looking for and if we change its value the same change can be seen in the game also. I try to change the value to $50k and found mine it’s 068D324C yours may be different. If all this not making sense see the snapshot below
Posted Image

Just to check our address is correct and it’s actually changing the amount of money we have in the game let’s set it to very low like $20 and try to build something oops we have insufficient funds which is exactly what we want to hear :D now make it  $10000 and try again yup it’s working we have our address. Note down this address quit the current match and start another match use different army and map this time I choose soviet. now in cheat engine you will see add address manually button click on it and add your address (mine is 068D324C) now change the value like before to $50k but it didn’t change on the game why? Because this game uses DMA and the address to money gets changed every time we start new match. So now we have to find a static reference which doesn’t change every time to calculate our address to money and such reference is called pointer. Pointers points to some address or may be another pointer which again points to some address and this address + offset = final address  and that’s what we are looking for, and how to do that is on next part.


Part 2 : Finding Base Pointer

To find the base pointer we need the current address of money, and as we changed the map the address is also changed so we have to repeat all part 1 to find the address. So go on and back with an address (mine is 05DDADD4 now) I hope you already add your address to the address list table if not do it plz and right click on it, you will see many options select Find out what writes to this address ,make sure your money is not increasing or decreasing while doing this

Posted Image

a window will pop-up do not close it and switch back to game again, spend some money and an address will be displayed to that pop-up of yours.

Posted Image

What we are doing is to find out what instruction is decreasing our money and if you wanna make sure just nop this instruction by clicking on the replace button it’ll change this instruction with one that do nothing. Let’s do it and after that try to build something as you can see no money is decreasing right now…..and you might think I don’t need to read further I got what I want but hold a sec champ, what we just did was a quick and dirty way we didn’t even know for what else this instruction is used for, and noping it might crash our game at some point. So let’s analyze what else this instruction do. To do so first we have to restore the original code by clicking on the advanced options at bottom of cheat engine you will see the instruction that we just noped now right click on it and select Restore with original code .
Posted Image

Ok our instruction has been restored now we going to set a breakpoint to it to do so first we need to open it inside a disassembler and thanks to dark byte the cheat engine has its own. You will find open the disassembler at this location option just above the Restore with original code click on it .And if this is our first time your expression might be “what the hell is this?” that is a disassembler every game hackers and crackers best buddy :D now before moving further let’s have a opponent in the game ,basically what I doubt is that same instruction is also responsible for decreasing our opponents money and if we simply nope it his money won’t decrease either ….so what’s the point then :D so go on start a new match with an opponent but wait a second what if he will crush us before we gather some data and another thing is we can’t see our opponent until the battlefield is expanded so what we can do is create a ally force and see it’s money is also manipulated by the same instruction, and if so it’s not a good idea to nop that because if it is holding our ally’s address it may be hold our opponents also. So go on and start a new match with an ally force. After starting the game don’t do anything just seat idle and let your ally start building something, in that way we are sure he is the one spending money right now. Now click on cheat engine’s memory view right click and select go to address enter 007F20D0 that’s the instruction which decrease our money. Now we are going to set a breakpoint on that instruction.Rightclick and select toggle breakpoint .
Posted Image

just after you click on the toggle breakpoint your game will be hang don’t panic it’s what a breakpoint do it stop all the dataflow to that instruction so we can azalyze it step by step. If  you can see the image above in the right side Registers are also shown and value of ESI is also shown there the value that ESI register holds is basically an address and if I am right it’s our ally’s money address. Well let’s see, if you read the instruction carefully
mov [esi+04],eax
means whatever value(address in our case) ESI reg. holds is added by 4 and then value of EAX reg. will copied to it. So for me ESI currently holds 0649A9C8+4 = 649A9CC (all calculation here are in hexadecimal you can use windows calculator to do hexadecimal calculations) and value of EAX is 2670 which is 9840 in decimal and that make sense as starting amount was 10000 he spent some money and 9840 remains in his account. But how can we sure that address 649A9CC(your will be different) is our ally’s lets add this address into address list of cheat engine by clicking on add address manually. Now change its value to 0 and freeze the address by clicking on the frozen checkbox, now remove the breakpoint from the instruction and run it by pressing F9 or debug->run option. Go back to game and analyze your ally’s activity and if you did everything right you will see all his constructions are stopped this moment that’s because we put 0 on his account, uncheck frozen and give him some big amount like $50k and see he will start making everything. So this analysis tells us the same instruction is used for player, his ally and opponent’s money. Now we can’t just nope this instruction we have to find out our base pointer and calculate our address every time. To calculate our base pointer first we need the current address that holds money you can do all the scanning one again or set a breakpoint to the instruction at  007F20D0 - 89 46 04 - mov [esi+04],eax and see what address ESI holds for you and add 4 to that address that will your current address for money. In my case it’s 067666C4 which is actually 067666C0+4 as its [ESI+4] now we have to find out what pointer points to the address that ESI holds currently. Just check on HEX checkbox and put your address of ESI reg. and click on new scan. I got only result(0558DDA8 for me) which is very good actually because that is our pointer but it may not the base pointer, so let’s scan for the address of pointer we just got .Again I got only one address(04A9BF94) not repeat this process until we found the base pointer.Ok we got no more address that hold 04A9BF94 that means that is our base pointer note it down. Remember this is a pointer to a pointer so when coding your hack you have to do
[value of (value of 04A9BF94 ) ]+4  = our address
To check it is a base pointer or not let’s EXIT the game and restart it again. add process of game to cheat engine now go to add address manually option click on pointer and put the address of base pointer we just found, see the image below for reference.

Posted Image

Now we have our base pointer and using this you can calculate address for money every time, You can stop right there if you want, just code a trainer that will write a very big value to this address like $999999. But if you stick with the tutorial we’ll going to learn how to use code injection and some assembly code, to stop decreasing the money.








Part 3 : Using Code Injection

As someone said a picture is worth thousand words here is an pictorial representation of what code injection is and how it works
Posted Image


Hope you get some idea of what we are going to do, first step is to wait and think what we actually want to do? And what we want to do here is simply change this instruction to something like.
  • If ESI == our address go to 3
  • Else go to 2
  • Decrease money value.
  • Jump back to original game code.
Now to write our code we need some free space. We can find that using cheat engine, go to memory view  and in menu you will see tools options in the top you will see two options 1’st is allocate memory and 2nd is scan for code caves. First one can be used for testing your code as it simply add some free memory but to write a trainer we have to search for code caves (this are the free spaces inside the game),so let’s search for code caves, I change the size to 40 from default 12 as I don’t know how much memory we need, but as more will be handy.

Posted Image

There are lots of space available  in the list and I pick 00D07000 (just because it is easy to remember) note down your address too. Now that we have an address to write our own code we can start but before creating the jump instruction on the original game route we must write the modified code first why? Because if we create a jump right now at 007F20D0 this will crash our game as the game is still running and we have nothing at 00D07000 but garbage only.
Here are the actual screenshot of the assembly code and I’ll explain each code step by step
Posted Image

Posted Image



Code Cave:
00D07000 – push eax “pushing the EAX register on the stack, so whatever value EAX currently holds will be saved and later restored, when we are done using EAX ”
00D07001-mov eax,[04a9bf94] “we are just copying the address value into EAX register that is pointed by our base pointer 04a9bf94”
00D07006 –mov eax,[eax] “again we are copying the value of (address value of EAX) in to EAX ,as we have a level 2 pointer, so basically EAX now holds our money address – 4(offset)”
Note: mov EAX,04a9bf94  - this copies simply a decimal value 78233492 to EAX;
Whereas mov EAX,[ 04a9bf94] – this copies whatever value 04a9bf94 address holds;
00D07008- cmp ESI,EAX “we are checking if the ESI holds our address, a cmp instruction return zero if true”
00D0700A-pop eax “now that we have no use of EAX we must restore its previous value.”
00D0700B-jne 00d07012 “this instruction means ‘jump if not zero’ if ESI not holds our address then compiler will jump to 00d07012”
00D0700D-jmp 00d07015 “this is a simple jump instruction that will jump on 00d07015. If ESI holds our address then this will execute”
00D07012 and 00D07015 are the actual game instructions at 007F20D0 and 007F20D3 , we have to mention this instructions because when we created a jump at 007F20D0 both the instructions were destroyed.
00D07018 – jmp 007F20D6 ‘’it’s not what you see on the pic but that’s the same instruction we are simply going back to original game route.”
Now pause the game and write all this instructions, and edit the instruction at 007F20D0 to jmp 00D07000 now go back to game again and build something your money won’t decrease but your ally’s will, you can check it by setting a breakpoint at  00D07008 and step by step executing the instructions.





Here's the PDF version of the same feel free to share and re-post as long as the original author name is mentioned :)
thank you

Attached File  Code Injection Tutorial by DEMETRON.pdf   1.68MB   79 downloads


#30855 [Trainer] JUST CAUSE 2 All versions And DLC + 30 Trainer CES/LinGon

Posted by LinGon on 25 March 2010 - 07:18 PM

This is a new updated + 27 Trainer for the game Just Cause 2 All version.


Released - 25 March - 2010


Updated - 2 May - 2010
Updated: improved some small things and added a couple of more options. last version will still be available for a little while.

Enjoy!




Important: Please Read Info First before running the trainer.
And Enjoy!




Special Creds and Greets to Veggy and to Alwaysnub who has helped me in the past
and ofcourse to everyone thats worth greeting.

Happy Cheating!
Thank you and Enjoy!

IMPORTANT: if ending up with problems not beeing able to get the trainer to work, then please do some research before posting to quick about problems you might aswell solve on your own.

Also note that post's for problems containing too little info or no info at all about what's wrong will be deleted.


Trainer has been tested and working on Windows 7 32 bit - Ultimate Edition.

IMPORTANT: To try keeping trainer threads clean of alternate questions regarding game hacking overall, i would appricate those questions not regarding help about the specific trainer would be posted in a seperate thread, and ask your questions there please.



The + 8 And a + 27 Trainer for Just Cause 2

More options was going to be included, but they will have to wait.
so this should make most who gets the trainer to work without any issues be satesfied finally.


Very Important: When using this trainer id recommend closing down all other apps you may have running in the background and start the trainer first then the game, or vice versa. but keep in mind the if you end up with having the trainer not working for you, then do aloot of reasearch yourself on what could be the cause to this. Or use another trainer, am not the only trainer maker in the world and i do this for free.  so keep this in mind before you post too quick about it not working for you. Il try help those who help's themselfs first. Any ussless post will be deleted, So make it good!
And make sure to read the included Info file before using the trainer. This is also very important if you want to get most out of it.

Thank you and Enjoy hopefully.

And also if it works for you, then please let me know, This will assure il be continuing what i do.

IMPORTANT: Updated 22 April: If you experiance Instant crashes with the + 27 Trainer, then Use the RT v2 version of the trainer, Some Options may or may not still cause a crash with the RT v2 trainer, but Most Essential options should cause No crash whatsoever now.
If no crashes accurs for you, then i recommend using the none RT version of the + 27 trainer.


#33913 Warhammer 40,000: Dawn of War - Soulstorm v1.4.0.0 STEAM PLUS 7

Posted by KEMiCZA on 13 August 2011 - 04:57 PM

Warhammer 40,000: Dawn of War - Soulstorm v1.4.0.0 STEAM PLUS 7

  Game: Warhammer 40,000: Dawn of War - Soulstorm
  Version: v1.4.0.0 STEAM
  Author: kemicza
  Date: 13/08/2011
  Type: FULL 7 Options
        request (ToxicTemplar)


    Hotkey   Toggle   No.   Option

    F1        YES      x     ENABLE THE TRAINER
    NUM1      YES      1     Unlimited Requisition
    NUM2      YES      2     Unlimited Power
    NUM3      YES      3     No Polulation Cap
    NUM4      YES      4     Unlimited Faith
    NUM5      YES      5     Instant Build
    NUM6      YES      6     Strong Army
    NUM7      YES      7     Instant Refills

Attached Files




#33223 [TRAINER] Crysis 2 v1.1.0.0 PLUS 19

Posted by KEMiCZA on 27 March 2011 - 09:25 AM

Crysis 2 v1.1.0.0 PLUS 19 TRAINER

  Game: Crysis 2
  Version: v1.1.0.0
  Author: kemicza
  Date: 28/03/2011
  Type: FULL 19 Options


    Hotkey   Toggle   No.   Option

    F1        YES      x     ENABLE THE TRAINER
    NUM1      YES      1     Unlimited Health
    NUM2      YES      2     Super Speed
    NUM3      YES      3     Easy Kills
    NUM4      YES      4     Unlimited Energy
    NUM5      YES      5     Super Jump
    NUM6      YES      6     No Reload
    NUM7      YES      7     No Enemy Fire
    NUM8      YES      8     Unlimited Ammo / Grenades
    NUM9      NO       9     Add Catalyst Points
    DIVIDE    NO       10    Unlock Nanosuit Customs
    MINUS     YES      11    Freeze Enemies
    F2        NO       12    Save Position
    F3        NO       12    Load Position
    F4        NO       12    Restore Position
    F5        NO       13    Teleport Enemies
    F6        YES      14    Invisibility
    F7        YES      15    Slow Motion Mode
    F8        YES      16    Steady Aim
    F9        NO       17    Increase Gravity
    F10       NO       17    Decrease Gravity
    F11       NO       17    Insane Gravity
    F12       NO       17    Normal Gravity
    MULTIPLY  YES      18    No Weapon Limit
    ADD       YES      19    Instant Reload

   No.09: Enable, then press H and your amount will be increased.
   
   No.10: Enable, then press H and close. Then reopen with H, and
          check that shit out <img src='http://www.gamehacking.com/public/style_emoticons/default/tongue.gif' class='bbc_emoticon' alt=':P' />.. That's what I'm talking abt

   No.13: If you're too lazy to walk to the enemy, you can use 
          this option to teleport them to you. Make sure that
          you're in a open place, likt outside.

   No.14: The AI will completely, but COMPLETELY, to the deepest
          level not detect you in whatever way. It is so deep that
          you will need to be carefull with it because the game 
          will need to be able to detect you in certain situations.

   No.17: The game will run much slower allowing you to focus your
          aim perfectly, watching the blood splatter out of his
          (yep, unfortunatelly there r no female enemies) brain!

   No.16: Weapons such as snipers, or zooming type, will have 
          complete steady aim. 

   No.17: Allows you to modify the games gravity <img src='http://www.gamehacking.com/public/style_emoticons/default/ohmy.gif' class='bbc_emoticon' alt=':o' />! A fun thing
          to do is to stand still, and shoot cars while in low
          gravity. Let them go in the air and then enable insane
          gravity! Then restore it back to normal gravity. Or
          combine this option with the slow motion mode for even
          more winning!

   No.18: Pick up as many weapons that you like.

  -----------------------------------------------------------------------
  | To unlock Console Commands you can get (only 2.95$) my unlocker at: |
  | http://cheatscapes.com/title_index.asp?titleID=307                  |
  -----------------------------------------------------------------------



For the fuckers out the I must admit two options out of this trainer were made by using the console. If you don't like that, then please do not use it. I DO NOT care you fucking piece of shits. The trainer works and it's free you fuckface, so don't complain.

Enjoy my friends

Updated bugfix for NanoSuit Unlocks!! Thanks for the feedback.

edit: Added a few notes on how to use the hotkey editor with this game. I'm going to test it on x64 as well, but it will take a few hours.

edit: tested on x64 and it works.

Attached Files




#32182 Understanding What Structures Mean in Relation to FPS Games

Posted by attilathedud on 29 December 2010 - 04:22 AM

There seems to be a trend these days of people not understanding what structures actually represent; what I mean by this can be best described by an example. Consider the following post on any game-hacking related board:

Hey guys, here's my method of displaying a cool glow around a player, simply place it in R_RenderScene:

for( int i = 0; i < cgs->maxPlayers; i++ )
{
	if( cg_entities[ i ].isAlive ) 
	{
		//some code
	}
}


Upon seeing this, most people know there will always be the required reply that goes like:

Hey dude cool code! I'm new to C++ but I put your code in [insert base here]'s base and got the following errors:

1>.\hook.cpp(67) : error C2065: 'cgs' : undeclared identifier
1>.\hook.cpp(67) : error C2227: left of '->maxPlayers' must point to class/struct/union/generic type
1>        type is ''unknown-type''
1>.\hook.cpp(68) : error C2065: 'cg_entities' : undeclared identifier
1>.\hook.cpp(68) : error C2228: left of '.isAlive' must have class/struct/union
Can you tell me what's wrong? Thanks!


The common answer to this is a link to Google - however, there is a problem with just throwing this out. Yes, a large percent of people who ask this generally do not know C++. But consider a small example quickly:

Hey guys, why is "received" spelled with "ei?" I thought it was always "ie?" Also, why is "weight" spelled this way too?


The symbolic response to this would of course, "Go to Google and learn English." But Google can only teach what most people know, in this case, "'I' before 'e' except after 'c'." This only answers half the question though, and the answer to the latter part lies in the extension of the phrase "... or after 'a' such as neighbour or weight." The problem is that much of the information that has to do with game-hacking is much like the lesser known extension of the above example - since not many people know it, there is not much information on it. And while knowing the former part, C++ in our case, is a necessity, it is not the full picture. As such, let us take some time to dive in an explore this example!

First off, if this code looks truly foreign to you, I strongly suggest you go to Google. Ignoring the actual internals, the code is basically:

loop while i is less than something
check some condition
do something if that condition is true


This should be obvious to anyone who has ever touched C++ code (or C code for that matter), so if this confuses you, seriously, go learn the basics of C++.

Now that we have gotten that out of the way... the majour problem - or benefit, depending how you look at it - with computers is that they are stupid. Yes, when it comes to anything relating to numbers or maths, a simple home PC has the power of about six million human brains. However, computers lack a key persona of the human mind: the ability to use deductive logic. For example, consider the following premise:

You are an American who has never learned any foreign languages. While out shopping, a man approaches you and asks, "Hallo, sprechen Sie Deutsch?" Initially you have no clue what he means, but quickly you try to obtain some clues that will help you translate the sentence to English - you see the man has a "Berlin-Regeln!" shirt on, and while you do not know what "Regeln" means, you know Berlin is a city in Germany, so this man might hail from there. You also remember your Dad once telling you that English has many Germanic roots, and much of English is derived from German. You go back to the sentence and can only assume that "Hallo" means "Hello," and "sprechen" kind of sounds like "speak." You have no clue what "Sie" could mean, but you remember a history book where Germany was labeled "Deutschland." With all this, you make the assumption that the man is asking "Hello, do you speak German?" You answer "no," spin around, and take his trousers.


Obviously that is a long and drawn out example - the normal human can figure out the sentence and answer in about thirty seconds. It does highlight two key features however:
1) The use of previous unrelated knowledge to solve the answer.
2) The ability to assume without knowing everything.

The problem with computers is they lack both these features - when a compiler sees something it does not know, it literally will just stop. This inherently has to do with the basic designs of any C++ compiler. For everything introduced that is not a reserved keyword (i.e. if, else, for) it needs to know exactly what it is (a variable, a function, a template, etc.) and how long it is. Why? Well, consider this simple example code:
#include <stdio.h>

int main( int argc, char* argv[ ] )
{
	printf( "%d", x );

	return 0;
}

For a moment, assume this compiles as-is. Now knowing that every C++ compiler converts its code to assembly, try to write the assembly output of the code inside main:
push x
push 0xDEADBEEF 	;location of string "%d"
call printf
add esp, 8
xor eax, eax
retn

* The "xor eax, eax" is to account for the return 0. Eax is used to represent return values in assembly, and xor'ing a register with itself with set it to 0. *

It is easy to look at this and go, "well I don't see what's wrong, x is just a variable, duh." The problem with this stems from the fact we are looking purely at the human-readable code; the computer never sees this. Without diving too much into assembly, an assembler converts human-readable assemble code into a series of op-codes that are then converted into binary by the computer. Let us now impose the op-codes to the left of the assembly:
???		push x
68 EFBEADDE	push 0xDEADBEEF
FF15 A0204000	call printf
83C4 08		add esp, 8
33C0		xor eax,eax
C3		retn

Why the "???" next to push x? This stems from the fact that there are three different forms of pushes, and without knowing what x is, the assembler has no idea which one to use. If we use a statement like:
int x = 5;

Directly above our printf call, then x will always be five, as such the push x will be converted to:
6A 05		push 5

But what if we do:
int d = 7;
int x = d;

Well then x will be a memory location, and we will get our code converted to:
68 01A101EB 	push 0xEBO1A1O1		;hypothetical location of 'd'

But both of those assume x is a constant value! What if x changes, and we have a branch before our printf? Then x will be most likely held in a register, and the push x will become:
53		push ebx

Without the ability to logically deduct, the computer has no clue what we intended to do, so to save ourselves from code that is not what we intended, the compiler throws us an error that "x" is undefined.

Let us take what we learned so far and apply it to our original example:
for( int i = 0; i < cgs->maxPlayers; i++ )
{
	if( cg_entities[ i ].isAlive ) 
	{
		//some code
	}
}

Hopefully after the previous example, we now know why the compiler is throwing errors - it has no clue what cgs, maxPlayers, cg_entites, or isAlive even are! So let us define them!

But do we even know what they are? This is where looking at the errors helps:
1>.\hook.cpp(67) : error C2227: left of '->maxPlayers' must point to class/struct/union/generic type
1>.\hook.cpp(68) : error C2228: left of '.isAlive' must have class/struct/union

We now should know (from our knowledge of C++ we picked up from Google) that both cgs and cg_entities are either classes, structures, or unions, and that isAlive and maxPlayers, by virtue of their association with the dot and arrow operators, are members of these classes, structures, or unions. But which of the three are cgs and cg_entities? It is very unlikely they are unions (as unions share the same spot for data, and that would not make much sense for a game), so that leaves classes and structures. This is where having the Quake 3 S.D.K. helps, which you can find on Google easily. After extracting it, open up cg_main.c, and on the first few lines there is a reference to CG_Init. If you have done any work on the Quake 3 engine, you should already know that CG_Init is called anytime a new level is loaded up, and if you did not know that, now you do. The first few lines again should catch your eye:
void CG_Init( int serverMessageNum, int serverCommandSequence, int clientNum ) {
	const char	*s;

	// clear everything
	memset( &cgs, 0, sizeof( cgs ) );
	memset( &cg, 0, sizeof( cg ) );
	memset( cg_entities, 0, sizeof(cg_entities) );
	memset( cg_weapons, 0, sizeof(cg_weapons) );
	memset( cg_items, 0, sizeof(cg_items) );

If you go to the definition of cgs, it should land you on:
cgs_t				cgs;

Follow the definition of cgs_t, and it should land you in cg_local.h, where we can see that all the majour entities (cgs_t, cg_t, centity_t, etc.) are structures.

* Before we continue, it is important to note that the names of these structures are rather insignificant. You could easily change cgs->maxPlayers to ilikecake->poopfarts; as long as you keep consistancy, it does not really matter. It is just a common standard to keep the original Quake 3 definition of these members to make it easy for others to follow your code. *

So now let us head back to our original project - to fix the errors we were having before, we simply have to properly define the elements we are using:
typedef struct {
	int maxPlayers;
} cgs_t;

typedef struct {
	int isAlive;
} centity_t;

Before we continue, we need to take a slight detour and talk about syntax. Considering our example again:
for( int i = 0; i < cgs->maxPlayers; i++ ){
		if( cg_entities[ i ].isAlive ){

		}
	}

Why use an arrow operator for cgs and a dot operator for cg_entities? And how does the arrow even work? Let us dive in for a look!

Consider the following code:
typedef struct {
	int x;
	int y;
} Point;

How do we reference each element? Anyone who has learned the basics of C knows this - we use the dot operator:
Point p = { 5, 5 };
p.x = 1;
p.y = 1;

But how does the dot operator work? To understand this, we must first understand what a structure is, and how the compiler interprets it. Like any variable declaration, the compiler treats code like this as a grab for a reserved space. Take a basic declaration:
int x;

Upon seeing this, the compiler will immediately grab a section of memory (say, 0x40000000) and then mark that this location is associated with the start of the data that is referenced by the symbol "x." It will then go through and change every reference to x to point to the beginning of that location. All it needs to do this is know the variable's size, and away it goes.

This works relatively the same with regards to structures; using our example from before:
Point p = { 5, 5 };
p.x = 1;
p.y = 1;

After grabbing a section of memory (using 0x40000000 again) our compiler will mark it as the beginning of the start of "p." However, the difference is while "x" is a single variable, and only four bytes, "p" contains two variables. As such, the compiler will reserve eight bytes (four for each variable, since an int is a dword). "p" is then treated as a constant pointer to the memory location 0x40000000. To reference elements of "p," we then use the dot operator - all this does is add the amount needed to get to the requested element, and then de-references it. For example, upon seeing "p.y," the compiler knows from our previous definition of a Point that the element "y" is four bytes away from the beginning. As such, the compiler will interpret "p.y" as "*(p+4)."

* The topic of pointers is too convoluted and long to nestle inside another article. There are already great articles on pointers though, so I suggest you read them! *

Consider another example:
typedef struct {
	int x;
	int y;
	char cake;
	char* moo;
} idkmybff;

idkmybff jill = { 1, 2, '3', "4" };

How would we reference the element "moo" directly? Using our past example as guidance, all we need to do is add the size of each element to the beginning of "jill:"
*( jill + 9 )

Now this presents an interesting point - a "char" is a single element long, and as such, can be used to fill up structures of unknown sizes beautifully. Keep this in mind for later!

Back to our original question, the meaning of the arrow operator; consider if you declared a pointer to a structure:
Point p = { 1, 1 };
Point *z = p;

How would you reference element "p.y" from z? Well, you would need to do:
(*z).y

And yes, the parenthesis are needed! Consider the case:
*z.y

With what we learned before of referencing elements in structures, this would evaluate as:
*(*z + 4 )

Which is probably not even valid as it de-refences the memory location held in "p.y" (in our case, 0x00000001).

Obviously, "(*z).y" is very error prone, and can lead to some annoying bugs, so to fix this, the arrow operator was invented. With the arrow, "(*z).y" turned into "z->y."

That is easy enough to follow, but then why does:
cg_entities[ i ].isAlive

Use a dot? The important part of the answer relies in the array subscript attached.

Let us again consider an easy example; take the following code:
int x[ 4 ] = { 0, 1, 2, 3 };

In many ways (at least for the sake of the tutorial), we can compare arrays to structures - when encountered, the compiler will grab the type of element, and how many, and reserve a section of memory for the array, making the symbol "x," in our case, a constant pointer to the start of that section. Sub-scripting is also just a system created for ease; it is easy to re-write any subscript using pointer notation:

x[ 0 ] = *x;
x[ 1 ] = *( x + 4 )
x[ 2 ] = *( x + 8 )
etc...


Going back to our original code, we can now translate this:

cg_entities[ i ] = *( cg_entities + ( i * sizeof( cg_entities) ) )


And then, we end up at the beginning of a normal structure (since we de-refenced our result already), and now all we need to do is add the length to get to the element isAlive.

Whew! That was quite a bit of math, but now we know just from looking at the code that cgs and cg_entities are pointers, and we can declare them as such:
	cgs_t * cgs;
	centity_t * cg_entities;

And now our code will compile fine. However, inject it all you want, it will not work, and for a very obvious reason: the pointers point to nothing! Remember when I told you that the naming convention does not matter? That is because when the compiler interprets our code, it will just strip our names and reference the symbols as memory addresses, and since they point to nothing (or garbage, depending on what compiler you use), you will not get the intended result. I can not stress how many times I have seen people make the mistake of thinking that just because you get the structures from a post, you are done - the structures mean nothing unless they point to the correct place! And why? Because our structures we use for our code are nothing but placeholders meant to represent the actual structures any Quake 3 engine game creates and stores! Heck, we do not even need them! If we know cgs begins at 0xDEADBEEF, and we know that cgs looks like:
typedef struct {
	int cake;
	int maxPlayers;
} cgs_t;

We could easily reference maxPlayers as *( 0xDEADBEEF + 4 )! Again, the only reason most people use structures is to make the code easier to develop and maintain!

... Sorry, I got a little insane there. Anywho, how do we find the actual memory locations of the real structures? Well, remember back to our trip in the Quake 3 S.D.K.:
void CG_Init( int serverMessageNum, int serverCommandSequence, int clientNum ) {
	const char	*s;

	// clear everything
	memset( &cgs, 0, sizeof( cgs ) );
	memset( &cg, 0, sizeof( cg ) );
	memset( cg_entities, 0, sizeof(cg_entities) );
	memset( cg_weapons, 0, sizeof(cg_weapons) );
	memset( cg_items, 0, sizeof(cg_items) );

Consider this code for an instant, and consider what we need; we need both the start location of each structure, and the size of each structure so we can reference them as an array, and for other reasons I will discuss in a moment. Well, we see that memset is passed the beginning of the structures in the first element, and the size in the last. Now if only we could find them...

... oh wait, obvious string a few lines down:
	s = CG_ConfigString( CS_GAME_VERSION );
	if ( strcmp( s, GAME_VERSION ) ) {
		CG_Error( "Client/Server game mismatch: %s/%s", GAME_VERSION, s );
	}

Let us now use Call of Duty 4 as a practical example of how to find the structures. Open up Olly, and load up Call of Duty 4. Search for all referenced text strings, and do a search for "Client/Server game mismatch." It should land you with one result:
Text strings referenced in iw3mp:.text, item 1603
 Address=00440045
 Disassembly=PUSH iw3mp.006CC274
 Text string=ASCII 15,"Client/Server game mi"

Follow it and you should land in:
00440045  |. 68 74C26C00    PUSH iw3mp.006CC274                      ;  ASCII 15,"Client/Server game mi"

Then scroll all the way up to the top of the function and you should find yourself within CG_Init:
0043FAD0  /$ 55             PUSH EBP                                 ;  CG_Init
0043FAD1  |. 8BEC           MOV EBP,ESP
0043FAD3  |. 83E4 F8        AND ESP,FFFFFFF8
0043FAD6  |. 83EC 44        SUB ESP,44

If we glance down, we should see something very suspicious:
0043FAD9  |. 53             PUSH EBX
0043FADA  |. 8B5D 08        MOV EBX,DWORD PTR SS:[EBP+8]
0043FADD  |. 56             PUSH ESI
0043FADE  |. 57             PUSH EDI
0043FADF  |. 68 243A0000    PUSH 3A24
0043FAE4  |. 33FF           XOR EDI,EDI
0043FAE6  |. 57             PUSH EDI
0043FAE7  |. 68 08A97400    PUSH iw3mp.0074A908
0043FAEC  |. E8 AFC92300    CALL iw3mp.0067C4A0
0043FAF1  |. 83C4 0C        ADD ESP,0C
0043FAF4  |. 68 F0E70F00    PUSH 0FE7F0
0043FAF9  |. 57             PUSH EDI
0043FAFA  |. 68 38E37400    PUSH iw3mp.0074E338
0043FAFF  |. E8 9CC92300    CALL iw3mp.0067C4A0
0043FB04  |. 8BC3           MOV EAX,EBX
0043FB06  |. 69C0 78160000  IMUL EAX,EAX,1678
0043FB0C  |. 83C4 0C        ADD ESP,0C
0043FB0F  |. 68 78160000    PUSH 1678
0043FB14  |. 8DB0 A86F7400  LEA ESI,DWORD PTR DS:[EAX+746FA8]
0043FB1A  |. 57             PUSH EDI
0043FB1B  |. 56             PUSH ESI
0043FB1C  |. 897424 18      MOV DWORD PTR SS:[ESP+18],ESI
0043FB20  |. E8 7BC92300    CALL iw3mp.0067C4A0
0043FB25  |. 8BCB           MOV ECX,EBX
0043FB27  |. 69C9 00700700  IMUL ECX,ECX,77000
0043FB2D  |. 83C4 0C        ADD ESP,0C
0043FB30  |. 68 00700700    PUSH 77000
0043FB35  |. 81C1 D8F28400  ADD ECX,iw3mp.0084F2D8
0043FB3B  |. 57             PUSH EDI
0043FB3C  |. 51             PUSH ECX
0043FB3D  |. E8 5EC92300    CALL iw3mp.0067C4A0
0043FB42  |. 8BD3           MOV EDX,EBX
0043FB44  |. 69D2 00220000  IMUL EDX,EDX,2200
0043FB4A  |. 83C4 0C        ADD ESP,0C
0043FB4D  |. 68 00220000    PUSH 2200
0043FB52  |. 81C2 58867400  ADD EDX,iw3mp.00748658
0043FB58  |. 57             PUSH EDI
0043FB59  |. 52             PUSH EDX
0043FB5A  |. E8 41C92300    CALL iw3mp.0067C4A0
0043FB5F  |. 83C4 0C        ADD ESP,0C
0043FB62  |. 68 000C0000    PUSH 0C00
0043FB67  |. 57             PUSH EDI
0043FB68  |. 68 202B7400    PUSH iw3mp.00742B20
0043FB6D  |. 891E           MOV DWORD PTR DS:[ESI],EBX
0043FB6F  |. E8 2CC92300    CALL iw3mp.0067C4A0
0043FB74  |. 83C4 0C        ADD ESP,0C
0043FB77  |. 68 E0000000    PUSH 0E0
0043FB7C  |. 57             PUSH EDI
0043FB7D  |. 68 402A7400    PUSH iw3mp.00742A40
0043FB82  |. E8 19C92300    CALL iw3mp.0067C4A0
0043FB87  |. 83C4 0C        ADD ESP,0C
0043FB8A  |. 68 40010000    PUSH 140
0043FB8F  |. 57             PUSH EDI
0043FB90  |. 68 409E8C00    PUSH iw3mp.008C9E40
0043FB95  |. E8 06C92300    CALL iw3mp.0067C4A0
0043FB9A  |. 83C4 0C        ADD ESP,0C
0043FB9D  |. 68 00030000    PUSH 300
0043FBA2  |. 57             PUSH EDI
0043FBA3  |. 68 D0397400    PUSH iw3mp.007439D0
0043FBA8  |. E8 F3C82300    CALL iw3mp.0067C4A0
0043FBAD  |. D9EE           FLDZ
0043FBAF  |. D915 68767900  FST DWORD PTR DS:[797668]
0043FBB5  |. 83C4 0C        ADD ESP,0C

Well how interesting! A series of calls to the same place that all push three elements! Time to find out where each of these addresses point to and what some of them are, in the case where Call of Duty 4 is pushing registers; place a hardware breakpoint on the first line (0043FAD9, push ebx), and go start a new server. After the loading finishes, Olly should pop to your breakpoint.

After stepping through all the calls, you should get the following information:
Structure	Location	Size
------------------------------------
???		74A908		3A24
???		74E338		FE7F0
???		746FA8		1678
???		84F2D8		77000
???		748658		2200
???		742B20		C00
???		742A40		E0
???		8C9E40		140
???		7439D0		300

Now all we have to do is find out what each of these are; delete your breakpoint, un-pause CoD4, and let it finish loading the level. Once you are in and on a team, bring up the dump, and go to the first location on our list: 74A908. You should see:
0074A908  00 00 00 00 00 00 00 00 00 04 00 00 00 03 00 00  ..............
0074A918  AB AA AA 3F 63 00 00 00 41 04 00 00 01 00 00 00  Â«ÂªÂª?c...A.....
0074A928  77 61 72 00 00 00 00 00 00 00 00 00 00 00 00 00  war.............
0074A938  00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00  ................
0074A948  43 6F 44 34 48 6F 73 74 00 00 00 00 00 00 00 00  CoD4Host........
0074A958  00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00  ................
0074A968  00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00  ................
0074A978  00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00  ................
0074A988  00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00  ................
0074A998  00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00  ................
0074A9A8  00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00  ................
0074A9B8  00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00  ................
0074A9C8  00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00  ................
0074A9D8  00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00  ................
0074A9E8  00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00  ................
0074A9F8  00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00  ................
0074AA08  00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00  ................
0074AA18  00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00  ................
0074AA28  00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00  ................
0074AA38  00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00  ................
0074AA48  18 00 00 00 6D 61 70 73 2F 6D 70 2F 6D 70 5F 63  ...maps/mp/mp_c
0074AA58  72 61 73 68 2E 64 33 64 62 73 70 00 00 00 00 00  rash.d3dbsp.....

Both the map name and the server name (CoD4Host is used for local servers) are present, which probably means we are in cgs (go verify in the Quake 3 S.D.K. if you do not believe me). While these are fine, what about the maximum number of players? Well, the default number is twenty-four, which is eighteen in hex. Knowing this, you can easily see the maximum number of players resides in 74A908+140! Go back to your cgs_t structure, which should look like:
typedef struct {
	int maxPlayers;
} cgs_t;

Remembering how structures and chars work, converting this to make sure that maxPlayers is always 0x140 away from the beginning location is easy - simply add the difference in with placeholders like so:
typedef struct {
	char unknown[ 320 ];
	int maxPlayers;
	char unknown2[ 14560 ];	//since the size is 3A24 - ( 140 + 4 )
} cgs_t;

* 320 = 0x140! Do not forget that Olly displays values in hexadecimal, not decimal! *

But we can do even better:
typedef struct {
	char unknown[ 64 ];
	char serverName[ 256 ];
	int maxPlayers;
	char mapName[ 64 ];
	char unknown2[ 14496 ];
} cgs_t;

The same method of debugging and referencing the Quake 3 S.D.K. can be used to fill in most of the structure easily.

But remember, our structure is only a placeholder, so before we precede, we need to make sure that we make our pointer point to the correct location:
cgs_t * cgs = ( cgs_t * ) 0x74A908;

The same method can be used to find our pointer to cg_entities, and to find where isAlive lies (looks for a value that alternates between 0x24 when alive, and 0 when dead). I will leave you to do this as practice for yourself, but you should end up with:
typedef struct {
	char unknown[ 400 ];
	int isAlive;
	char unknown2[ 0x76E6C ]; 
} centity_t;

centity_t * cg_entities = ( centity_t * ) 0x84F2D8;

And that is all there is to it. Hopefully now the mystery has been removed and we can stop seeing those oh-so-annoying posts.

Until next time,
attilathedud


#17380 Gamehacking Tools

Posted by Psych on 16 November 2008 - 10:09 AM

Gamehacking Tools

I have compiled a short-list of the most commonly used and useful gamehacking-related tools. Not all of these tools are freeware. All of the links below link directly to the authors homepage, and not any 3rd party site (with a couple of exceptions only). None of them are direct-links; authers don't like that, and we will not PM you with warez, so don't even bother sending such requests. If any links become broken please PM me or a mod/admin so it can be amended.

**All files have been multi-scanned and were found be be clean**
Feel free to check them yourself, Here, and Here.



Memory Scanners/Editors

- Cheat Engine
- ArtMoney
- T-Search
- MemoryHackingSoftware
- Cheat O' Matic
- Game Cheater


Debuggers

- OllyDBG
- IDA Pro
- Syser Debugger
- WinDBG
- Immunity Debugger


Trainer Makers

- Game Trainer Studio
- Cheat Engine
- Magic Trainer Creator
- MemHack
- Trainer Creation Kit
- Trainer Maker Kit


Hex Editors

- Hex Workshop
- XVI32
- AXE Hex Editor
- WinHex
- HxD
- DataWorkshop
- FlexHEX
- HIEW


Packet Analyzers/Editors

- WPE/WPE Pro
- Psy Pro (Modified WPE for AC Bypass)
- Redox Packet Editor
- Wireshark (Ethereal)
- Nsauditor
- Sniffer Basic (NetXray)


Windowing Tools

- DXWnd
- 3DAnalzer
- D3DWindower
- WindowMe for DirectX apps (modified DXWnd)


Miscellaneous
(Upload by me as DL links are seriously lacking - .7z archives)

- Game Minimizing Tools (Anti Alt-Tab, MHT, MinimizatoR)
~Thanks mAURIZIO cAMPO, Tsonkie, Guru.eXe

- Code-Caving tools (SAS, CodeCaver, CCT)
~Thanks [Sheep], Spookie, Tsongkie

- Caption Changer (~Thanks STN)

- LordPE (great multi-purpose PE tool)

- SaveGame Analyser

- Winject v1.7b (~Thanks mcMike)

- TrainerSpy / Modified TSpy (~Thanks BofeN & Me)

- Dragon Unpacker (Game Archive Unpacker/Extractor)

- Trainer Spy Kit v3 (Fix2)



**Last Updated Xmas '09


#35488 How to Write a Basic Disassembler

Posted by attilathedud on 08 August 2012 - 06:37 AM

A man is only as good as his tools - this, however, does not give him an excuse to be willfully ignorant of what his tools do! In that spirit, let us sprint onto the road of discovery and explore the internals of disassembling.

* On a side note, I do ask you to excuse any rust that has seemed to creep up on me with age! *

Most of us have experience with disassembling - hell, OllyDbg's main view is nothing but disassembly! And yes, before the cries emerge, there are technical differences between assembly and disassembly, though minute, that make both worthy of their own category (the biggest of these being lack of comments, original labels, and original function calls in disassembly). But do not fret, as writing a dis-assembler is actually far easier than one thinks (especially for those who have experience with DFA machines!)

* Before we continue, I would like to address an issue that seems to plague the internet:
    - Assembly
    - Assembler
    - assembling
    
These words do not mean the same thing (and eo ipso disassembly, dis-assembler, and disassembling do not either), but it is an easy mistake to make. Assembly (I vaguely recall writing about this before) is the language, in the same vain as C, Java, Ruby, etc. - an assembler is the program that converts assembly into an object file (much like a compiler for high-level languages). You wouldn't call C++ "Compiler," so make the weakened Assembly gods happy by not calling Assembly "Assembler." As for the last term, that is the present-tense verb for the process of an assembler; when running an assembler, you are assembling the code. *

Despite its name, it is easiest to think of disassembling as a process of reconstruction, whereby we build a program back up from just bytes. And, like most reconstruction processes, our job will be infinitely easier if we understand how the sad program got to its current state.

* Please note that like pointers, this is a topic people have written entire theses on. The fact that my explanation will be little more than a paragraph should let you know that it is not comprehensive at all. *

Modern compilers (thankfully) take much of the work out of building a program - you include all your files in a project, hit "Build," and magically an executable appears. Behind the scenes, the build process itself consists of the four main steps:

1. Preprocessing
2. Compiling
3. Assembling
3. Linking

* For this example, we will assume a traditional structure high-level language (or HLL) such as C or C++. For comparison, Java undergoes a similar process, the compiling step producing byte-code instead of an object file (which is then executed by the JVM). I must admit I am less familiar with scripting languages, but they often skip the last three steps and instead execute their code dynamically, usually through use of a basic emulator or state machine. *

The preprocessor goes through your code and rips out everything the computer doesn't care about - namely comments, white-space, and various other non-code elements. It will also go through and replace bits of your code (e.g., replacing #defined elements with their true data, substituting constants in where it makes sense, and optimising code). How far it goes depends on the compiler, as some will compile your code as-is, and others will replace statements like:
int x = 5;
if( i == x )
{ ... }

With:
if( i == 5 )
{ ... }

Though I speak like this of one step, this process is normally broken up into several different tasks, executing different tools at each part, and reiterating through many of the steps multiple times (especially when it comes to optimising code - often different tools will be responsible for optimising loops, conditionals, etc.)

The code then goes to the second step, compiling, which will translate the code to assembly. As an example:
if( i == 5 )
{

}

I touched briefly on keywords in a previous tutorial, and this is why they are important, as the compiler can only translate things it has well-defined explanations of. Upon hitting our code, the compiler will match to an if conditional, and substitute in the following assembly:
mov eax, dword ptr ds:[0x101EBO1A] //example location of i
cmp eax, 5
jne _false
;body of the conditional
_false:

Remember when I talked about things the preprocessor rips out? Variables are another one of those things us stupid humans need - the computer just substitutes in their memory addresses. So really, the code coming into the compiler would look like:
if( *0x101EBO1A == 5 )
{

}

Following this, the code will again be run through a series of optimisers before arriving at the assembler which will assemble the code generated from compiling and produce an object file. An object file for all intents and purposes is an executable file, except for three (albeit, huge) differences:

1. No external calls to libraries point to correct locations.
2. No calls to other object files are valid. (Remember, an object file is created for each .c (or likewise) file!)
3. The file is not packed in a valid executable format.

Enter the linker, which links the calls in the object file to the correct libraries and packs the program to run on the target system (for Windows, the PE format).

Shew, that was quite the process - and what do we even get for so much work! Just a bunch of bytes! Outrageous!

This is actually an important thing to keep in mind - though executables have magic properties, they are nothing more than a series of bytes with a well-documented format. I promise you, no scary monsters lurking in there!

* For the rest of this tutorial we will be using the following code to test on:
.486
.model flat,stdcall
option casemap:none

include \masm32\include\windows.inc
include \masm32\include\kernel32.inc
includelib \masm32\lib\kernel32.lib
include \masm32\include\user32.inc
includelib \masm32\lib\user32.lib

.code
    _start:
    
        xor eax,eax
        mov eax,5
        mov ebx,8
        push eax
        pop eax
        xor eax,eax
        
        xor ebx,ebx
        test ebx,ebx
        test eax,eax
        push ebx
        pop ebx
        
        cmp ebx,0
        cmp eax,0
        je @_moo
    
        push 1
        push 0
        push 0
        push 0
        call MessageBoxA
        
        push 4Dh
        call GetAsyncKeyState
        
        push 0
        push 0
        push 0
        push 0
        call ReadFile
        
        @_moo:
        
        push 0
        call ExitProcess
    
    end _start

It does nothing, but it provides us a good base of instructions to test our dis-assembler on. Assembly is the language of choice - both to give us increased visibility of our progress and to ensure that mean Mr. Compiler doesn't destroy our code. You can either compile this yourself using masm32, or download the program "test.exe" attached to this post. *

Before we try to disassembly this, let us calm our nerves and start out just dumping the bytes of the file to reaffirm our previous point that executables are nothing but some lame bytes.

Create a console application, set it up as an empty project, add a "main.cpp," and then add the following code:
#include <stdio.h>
#include <Windows.h>

int main( int argc, char** argv )
{
    FILE *f = NULL;
    BYTE buffer[ 4096 ] = { 0 };

    f = fopen( "test.exe", "r" );
    
    if( f != NULL )
    {
        fread( buffer, 4096, 1, f );
        fclose( f );
        
        for( int i = 0; i < 4096; i++ )
        {
            if( buffer[ i ] != 0x00 )
                printf( "%X", buffer[ i ] );
            else
                printf( " " );
        }
    }
    else
    {
        printf( "File Not Found" );
    }

    getchar( );
    
    return 0;
}

* Remember kids, hard-coding things is bad, but we are just testing ideas here, so we can get away with it. *

* Make sure to adjust fopen to open to wherever you placed test.exe! *

This program is rather basic - it simply reads in all the bytes of a file, and then displays their hexadecimal form, with the caveat that it will skip null bytes (to help us distinguish different sections). Running the program will produce the following output:

Posted Image

Why highlight that random section in red? Well if we open up our program in Olly...

Posted Image

... we will see that our original thesis of programs not being magical are correct, as the opcodes for each instruction are stored in plain-sight!

Now, of course, the question arises of what an opcode is - I suppose we can stop being the cool kids and label it by its true term, "operation code." For each assembly instruction (push, mov, cmp, etc.) there exists a set of bytes that "represent" that instruction to the processor - to elaborate, when the processor is running our code and encounters 0x33C0, it knows that it needs to push eax on the stack. When it encounters 0xE8, it knows it needs to shift EIP to point to a new line of code. And so on, and so forth. Keep in mind that these opcodes shift for each processor - most modern Windows machines use the x86/x64 architecture as their foundation. While we could cover the internals of each processor and how they work, such a thing will wait for a different day.

* "But, but, attila! I thought programs were all in binary!" Well yes, but they are also in hexadecimal - I've done too much homework with this to ever want to approach the issue again, but it is important to remember that the difference between our view and binary is just in the way it is represented. The same opcodes are present in the binary form, just represented with 0's and 1's.

As an analogy, imagine the following - "three," "3," "5-2:" we see three ways of representing three. One is in English, one in the decimal system, and one represented in equation form - three different mediums. Despite this, the data is still the same - likewise with our previous argument with hexadecimal and binary. *

So we know our code is in there, but what remains of all the crap cluttered at the top? Enter the PE header (it would appear the linker has competition).

To admit my faults, my versatility with the PE header is rather limited, but here is a crash course on it: in the most basic of senses, the PE header contains all the information that Windows needs to load and execute the code correctly, including sections, references to external libraries, data, and random other bits of information. It's basic layout is as follows:

Posted Image

* For a more detailed look at the PE structure and format, check out Icezlion's series on it at http://win32assembly...fr/pe-tut1.html (to view other sections of it, change the 1 at the end). *

We could care less about the DOS header, other than its e_lfanew member which points to the start of the NT header. Of the NT header, we are primarily concerned with section-related stuff.

Before we get carried away with sections, however, let us slightly modify our original file dumper and reanalyse our executable to get a feel of the format:
#include <stdio.h>
#include <Windows.h>

int main( int argc, char** argv )
{
    FILE *f = NULL;
    BYTE buffer[ 4096 ] = { 0 };

    f = fopen( "test.exe", "r" );
    
    if( f != NULL )
    {
        fread( buffer, 4096, 1, f );
        fclose( f );
        
        for( int i = 0; i < 4096; i++ )
        {
            //if( buffer[ i ] != 0x00 )
                printf( "%X", buffer[ i ] );
            //else
                //printf( " " );
        }
    }
    else
    {
        printf( "File Not Found" );
    }

    getchar( );
    
    return 0;
}

* Yes, all we are doing here is commenting out the code and printing everything.*

This will produce the following result:
Posted Image

We see that one part of that big hunk of crap is the PE header (highlighted in red), complete with the DOS magic number and PE magic number, which are nothing more than some bytes that label valid PE files. The purple highlights our first section header, but let us delay again and instead write some code to read the PE header!

* Most of this is just Icezelion's code converted to C. *

#include <Windows.h>
#include <stdio.h>

int main( int argc, char** argv )
{
    HANDLE hFile = NULL, hFileMappingObject = NULL;
    LPVOID base = NULL;

    PIMAGE_DOS_HEADER image_dos_header;
    PIMAGE_NT_HEADERS image_nt_header;
    PIMAGE_SECTION_HEADER image_section_header;

    hFile = CreateFile( "test.exe", GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL );

    if( hFile != INVALID_HANDLE_VALUE )
    {
        hFileMappingObject = CreateFileMapping( hFile, NULL, PAGE_READONLY, 0, 0, NULL );

        base = MapViewOfFile( hFileMappingObject, FILE_MAP_READ, 0, 0, 0 );

        image_dos_header = (PIMAGE_DOS_HEADER) base;

        if( image_dos_header->e_magic != IMAGE_DOS_SIGNATURE )
        {
            printf( "DOS magic number invalid" );
            UnmapViewOfFile( base );
            CloseHandle( hFileMappingObject );
            CloseHandle( hFile );
            getchar();
            return 0;
        }

        image_nt_header = (PIMAGE_NT_HEADERS) ((DWORD)base + image_dos_header->e_lfanew );

        if( image_nt_header->Signature != IMAGE_NT_SIGNATURE )
        {
            printf( "Not a valid PE file" );
            UnmapViewOfFile( base );
            CloseHandle( hFileMappingObject );
            CloseHandle( hFile );
            getchar( );
            return 0;
        }

        //read in our sections

        UnmapViewOfFile( base );
        CloseHandle( hFileMappingObject );
        CloseHandle( hFile );
    }

    getchar();

    return 0;
}

* If Visual Studio complains about "test.exe", Right-click on project->Select Properties->and Select Use Multi-Byte Character Set. *

I typically like to avoid throwing out large sections of code, but if we take this line-by-line, it will be less of a shock!
    HANDLE hFile = NULL, hFileMappingObject = NULL;
    LPVOID base = NULL;

    PIMAGE_DOS_HEADER image_dos_header;
    PIMAGE_NT_HEADERS image_nt_header;
    PIMAGE_SECTION_HEADER image_section_header;

The two handles will be placeholders for CreateFile and CreateFileMapping. Base will contain the base address of our file when mapped into memory, and will be the basic block we reference everything with.

As for the three latter elements, they represent data structures that model the DOS, PE, and Section headers. They are declared as pointers (since we will have them point at specific memory from the mapping).

    hFile = CreateFile( "test.exe", GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL );

    if( hFile != INVALID_HANDLE_VALUE )
    {

CreateFile will return a handle to our opened file, similar to fopen. So then why CreateFile? Because we need a handle for CreateFileMapping, and because CreateFile will allow us to easily modify our file pointer (current location in the file) so that we can easily jump around when reading the data in.

        hFileMappingObject = CreateFileMapping( hFile, NULL, PAGE_READONLY, 0, 0, NULL );

        base = MapViewOfFile( hFileMappingObject, FILE_MAP_READ, 0, 0, 0 );

        image_dos_header = (PIMAGE_DOS_HEADER) base;

CreateFileMapping will simply create a file mapping object for a file, which we will then pass into MapViewOfFile, which will load the file into memory and return the starting address of our mapped data. Since the DOS header is the first element of any PE file, it would make sense to point our DOS Header structure to the base.

        if( image_dos_header->e_magic != IMAGE_DOS_SIGNATURE )
        {
            printf( "DOS magic number invalid" );
            UnmapViewOfFile( base );
            CloseHandle( hFileMappingObject );
            CloseHandle( hFile );
            getchar();
            return 0;
        }

Just to make sure, we check to make sure our DOS magic number is present, and that this is a valid DOS file. If not, we bail and clean up everything.

        image_nt_header = (PIMAGE_NT_HEADERS) ((DWORD)base + image_dos_header->e_lfanew );

        if( image_nt_header->Signature != IMAGE_NT_SIGNATURE )
        {
            printf( "Not a valid PE file" );
            UnmapViewOfFile( base );
            CloseHandle( hFileMappingObject );
            CloseHandle( hFile );
            getchar( );
            return 0;
        }

Next we do a similar process with the NT header, taking into account that the e_lfanew in the DOS header points to the NT header, and adding that to base. We then check to make sure this is actually a PE file.

If everything works, you should be able to open a variety of files (change test.exe to point to things like pdfs), and verify that our program picks out files that aren't executables!

I have now succeeded in substantially delaying talking about sections - for no good reason either! The section table is just an array of sections, where sections are just grouping of data by their common attributes (think .text, .rsrc, etc.). As referenced in the diagram earlier, a section is made up of a section header, which contains various tidbits (like name, size, and address) and the raw data that makes up the section.

* I cannot write with Korean music in the background. *

Since programs are made up of multiple sections, we now want to leverage our data to walk the section table:

* Ever want to sound like you know what you're talking about? Throw around the term "walking the section table" liberally. *

    int numOfSections = 0;
    DWORD preferredBase = 0, sectionHeaderBase = 0;
    ...
        //read in our sections
        numOfSections = image_nt_header->FileHeader.NumberOfSections;

        preferredBase = image_nt_header->OptionalHeader.AddressOfEntryPoint + image_nt_header->OptionalHeader.ImageBase;

        sectionHeaderBase = (DWORD)base + image_dos_header->e_lfanew + sizeof( IMAGE_NT_HEADERS );

There are three steps to this code:

1. First, we read the total number of sections from the NT header, so that we know how many times to iterate, then
2. We grab the preferred base of the application, by adding the base of the image and the application's entry point. This isn't directly related to the section table, but we will need it later.
3. Finally, we grab the base of the first section header, which directly follows the NT header.

With all that in hand, we can now iterate through all the sections, and start displaying information on them!

        for( int i = 0; i < numOfSections; i++ )
        {
            image_section_header = (PIMAGE_SECTION_HEADER) sectionHeaderBase;

            printf( "%s %x %x %x %x %x\n", image_section_header->Name, image_section_header->Misc.VirtualSize,
                image_section_header->VirtualAddress, image_section_header->SizeOfRawData, image_section_header->PointerToRawData,
                image_section_header->Characteristics );
                
            //find our section data
            
            //parse our data
            
            sectionHeaderBase += sizeof( IMAGE_SECTION_HEADER );
        }

We do not need all these elements, but it’s a good idea to print them to make sure we are pulling down everything correctly. If we run the code, we are presented with the following:

Posted Image

It looks like our test application has three sections (we primarily care about .text for now, since that houses the code). If we take one last trip back to our file dumper - I promise this is the last - we see the following:

Posted Image

Guess what 2e74657874 is in ascii!

* It's .text. I knew you weren't going to look it up. *

We are finally pulling down our data correctly, so let us now finish this dis-assembler up by both finding the relevant section data and parsing it (lots of code incoming):

    BYTE *buffer = NULL;
    DWORD dwBytesRead = 0;
    ...
    for( int i = 0; i < numOfSections; i++ )
        {
            image_section_header = (PIMAGE_SECTION_HEADER) sectionHeaderBase;

            printf( "%s %x %x %x %x %x\n", image_section_header->Name, image_section_header->Misc.VirtualSize,
                image_section_header->VirtualAddress, image_section_header->SizeOfRawData, image_section_header->PointerToRawData,
                image_section_header->Characteristics );
                
            //find our section data
            buffer = new BYTE[ image_section_header->SizeOfRawData ];

            SetFilePointer( hFile, image_section_header->PointerToRawData, NULL, FILE_BEGIN );

            ReadFile( hFile, buffer, image_section_header->SizeOfRawData, &dwBytesRead, NULL );
            
            //parse our data
            for( int j = 0; j < image_section_header->SizeOfRawData; j++ )
            {
                printf( "%x:\t", preferredBase + j );
                if( buffer[ j ] == 0x33 )
                {
                    printf( "xor " );
                    if( buffer[ j + 1] == 0xC0 )
                        printf("eax,eax" );
                    else if( buffer[ j + 1] == 0xDB )
                        printf("ebx,ebx" );
                    printf( "\n" );
                    j++;
                }
                else if( buffer[ j ] == 0x83 )
                {
                    printf( "cmp" );
                    if( buffer[ j + 1 ] == 0xFB )
                        printf( " ebx, %x", buffer[ j + 2 ] );
                    else if( buffer[ j + 1 ] == 0xF8 )
                        printf( " eax, %x", buffer[ j + 2 ] );
                    printf( "\n" );
                    j += 2;
                }
                else if( buffer[ j ] == 0x85 )
                {
                    printf( "test " );
                    if( buffer[ j + 1 ] == 0xDB )
                        printf( "ebx,ebx" );
                    else if( buffer[ j + 1] == 0xC0 )
                        printf("eax,eax" );
                    printf( "\n" );
                    j++;
                }
                else if( buffer[ j ] == 0x74 )
                {
                    printf( "je short %x\n", preferredBase + j + 2 + buffer[ j + 1 ] );
                    j++;
                }
                else if( buffer[ j ] == 0x53 )
                {
                    printf( "push ebx\n" );
                }
                else if( buffer[ j ] == 0xB8 )
                {
                    printf("mov eax,%x\n", buffer[ j + 1 ] );
                    j+=4;
                }
                else if( buffer[ j ] == 0xBB )
                {
                    printf("mov ebx %x\n", buffer[ j + 1 ] );
                    j+=4;
                }
                else if( buffer[ j ] == 0x50 )
                {
                    printf("push eax\n" );
                }
                else if( buffer[ j ] == 0x58 )
                {
                    printf("pop eax\n" );
                }
                else if( buffer[ j ] == 0x6A )
                {
                    printf( "push %d\n", buffer[ j + 1 ] );
                    j++;
                }
                else if( buffer[ j ] == 0x5B )
                {
                    printf( "pop ebx\n" );
                }
                else if( buffer[ j ] == 0xE8 )
                {
                    printf( "call %x%x%x%x\n", buffer[ j + 1 ], buffer[ j + 2 ], buffer[ j + 3 ], buffer[ j + 4 ] );
                    j+=4;
                }
                else if( buffer[ j ] == 0xFF && buffer[ j + 1 ] == 0x25 )
                {
                    printf( "jmp dword ptr ds:[%x%x%x%x]\n", buffer[ j + 2 ], buffer[ j + 3], buffer[ j + 4 ], buffer[ j + 5 ] );
                    j+=5;
                }
                else
                    printf( "db %x\n", buffer[ j ] );
            }

            printf("----------------------------------------------------------------\n" );
            
            delete[] buffer;

            sectionHeaderBase += sizeof( IMAGE_SECTION_HEADER );
        }

Again, let us take this step-by-step:
            buffer = new BYTE[ image_section_header->SizeOfRawData ];

            SetFilePointer( hFile, image_section_header->PointerToRawData, NULL, FILE_BEGIN );

            ReadFile( hFile, buffer, image_section_header->SizeOfRawData, &dwBytesRead, NULL );

This section is rather straight-forward - we initialise a buffer the size of the section's data, point our file pointer to where our raw data resides (in our case, the code), and then read the code into the buffer.

Now for the parsing:
            for( int j = 0; j < image_section_header->SizeOfRawData; j++ )
            {
                printf( "%x:\t", preferredBase + j );
                if( buffer[ j ] == 0x33 )
                {
                    printf( "xor " );
                    if( buffer[ j + 1] == 0xC0 )
                        printf("eax,eax" );
                    else if( buffer[ j + 1] == 0xDB )
                        printf("ebx,ebx" );
                    printf( "\n" );
                    j++;
                }
                else if( buffer[ j ] == 0x83 )
                {
                    printf( "cmp" );
                    if( buffer[ j + 1 ] == 0xFB )
                        printf( " ebx, %x", buffer[ j + 2 ] );
                    else if( buffer[ j + 1 ] == 0xF8 )
                        printf( " eax, %x", buffer[ j + 2 ] );
                    printf( "\n" );
                    j += 2;
                }
                else if( buffer[ j ] == 0x85 )
                {
                    printf( "test " );
                    if( buffer[ j + 1 ] == 0xDB )
                        printf( "ebx,ebx" );
                    else if( buffer[ j + 1] == 0xC0 )
                        printf("eax,eax" );
                    printf( "\n" );
                    j++;
                }
                else if( buffer[ j ] == 0x74 )
                {
                    printf( "je short %x\n", preferredBase + j + 2 + buffer[ j + 1 ] );
                    j++;
                }
                else if( buffer[ j ] == 0x53 )
                {
                    printf( "push ebx\n" );
                }
                else if( buffer[ j ] == 0xB8 )
                {
                    printf("mov eax,%x\n", buffer[ j + 1 ] );
                    j+=4;
                }
                else if( buffer[ j ] == 0xBB )
                {
                    printf("mov ebx %x\n", buffer[ j + 1 ] );
                    j+=4;
                }
                else if( buffer[ j ] == 0x50 )
                {
                    printf("push eax\n" );
                }
                else if( buffer[ j ] == 0x58 )
                {
                    printf("pop eax\n" );
                }
                else if( buffer[ j ] == 0x6A )
                {
                    printf( "push %d\n", buffer[ j + 1 ] );
                    j++;
                }
                else if( buffer[ j ] == 0x5B )
                {
                    printf( "pop ebx\n" );
                }
                else if( buffer[ j ] == 0xE8 )
                {
                    printf( "call %x%x%x%x\n", buffer[ j + 1 ], buffer[ j + 2 ], buffer[ j + 3 ], buffer[ j + 4 ] );
                    j+=4;
                }
                else if( buffer[ j ] == 0xFF && buffer[ j + 1 ] == 0x25 )
                {
                    printf( "jmp dword ptr ds:[%x%x%x%x]\n", buffer[ j + 2 ], buffer[ j + 3], buffer[ j + 4 ], buffer[ j + 5 ] );
                    j+=5;
                }
                else
                    printf( "db %x\n", buffer[ j ] );

* I'm sorry for using lots of if's, don't kill me! *

* This is literally the worst way of doing this. Switches, pointers, or leveraging arrays would have been much better. I am lazy. *

* And no, this is not the complete instruction set, but you are always free to expand it! *

The story of this code is as follows: since we now possess all our data in a buffer, we loop through the buffer's size, examining each byte for know opcodes and on a known one print out the resulting assembly code. We also use our preferred base we got earlier to give an address to each byte of data. I pulled the opcodes from Olly, but a better place would be the Intel's Developer Manual.

You will notice if you try to run this, the output will flow off the screen - to get around this we will make use of piping to place our output in a file:
Posted Image

If everything went well, opening the file should be sight for sore eyes:
Posted Image

Now let us test how our dis-assembler does at reading data - change the CreateFile line so we can give it input:
    hFile = CreateFile( argv[ 1 ], GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL );

test2.exe is as follows, and can also be found attached:
.486
.model flat,stdcall
option casemap:none

include \masm32\include\windows.inc
include \masm32\include\kernel32.inc
includelib \masm32\lib\kernel32.lib

.data
candy dd 1
moo dd 2

.code
    _start:
	    xor eax,eax
	    push 0
	    pop eax
	    push ebx
	    pop eax
	    xor eax,eax

	    push 0
	    call ExitProcess
    end _start

We then execute our new command:
Posted Image

And scroll down to the .data section to see our variables:
Posted Image

The final code for comparison:
#include <Windows.h>
#include <stdio.h>

int main( int argc, char** argv )
{
    HANDLE hFile = NULL, hFileMappingObject = NULL;
    LPVOID base = NULL;

    int numOfSections = 0;
    DWORD preferredBase = 0, sectionHeaderBase = 0;

    BYTE *buffer = NULL;
    DWORD dwBytesRead = 0;

    PIMAGE_DOS_HEADER image_dos_header;
    PIMAGE_NT_HEADERS image_nt_header;
    PIMAGE_SECTION_HEADER image_section_header;

    hFile = CreateFile( argv[ 1 ], GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL );

    if( hFile != INVALID_HANDLE_VALUE )
    {
        hFileMappingObject = CreateFileMapping( hFile, NULL, PAGE_READONLY, 0, 0, NULL );

        base = MapViewOfFile( hFileMappingObject, FILE_MAP_READ, 0, 0, 0 );

        image_dos_header = (PIMAGE_DOS_HEADER) base;

        if( image_dos_header->e_magic != IMAGE_DOS_SIGNATURE )
        {
            printf( "DOS magic number invalid" );
            UnmapViewOfFile( base );
            CloseHandle( hFileMappingObject );
            CloseHandle( hFile );
            getchar();
            return 0;
        }

        image_nt_header = (PIMAGE_NT_HEADERS) ((DWORD)base + image_dos_header->e_lfanew );

        if( image_nt_header->Signature != IMAGE_NT_SIGNATURE )
        {
            printf( "Not a valid PE file" );
            UnmapViewOfFile( base );
            CloseHandle( hFileMappingObject );
            CloseHandle( hFile );
            getchar( );
            return 0;
        }

        //read in our sections
        numOfSections = image_nt_header->FileHeader.NumberOfSections;

        preferredBase = image_nt_header->OptionalHeader.AddressOfEntryPoint + image_nt_header->OptionalHeader.ImageBase;

        sectionHeaderBase = (DWORD)base + image_dos_header->e_lfanew + sizeof( IMAGE_NT_HEADERS );

        for( int i = 0; i < numOfSections; i++ )
        {
            image_section_header = (PIMAGE_SECTION_HEADER) sectionHeaderBase;

            printf( "%s %x %x %x %x %x\n", image_section_header->Name, image_section_header->Misc.VirtualSize,
                image_section_header->VirtualAddress, image_section_header->SizeOfRawData, image_section_header->PointerToRawData,
                image_section_header->Characteristics );
                
            //find our section data
            buffer = new BYTE[ image_section_header->SizeOfRawData ];

            SetFilePointer( hFile, image_section_header->PointerToRawData, NULL, FILE_BEGIN );

            ReadFile( hFile, buffer, image_section_header->SizeOfRawData, &dwBytesRead, NULL );
            
            //parse our data
            for( int j = 0; j < image_section_header->SizeOfRawData; j++ )
            {
                printf( "%x:\t", preferredBase + j );
                if( buffer[ j ] == 0x33 )
                {
                    printf( "xor " );
                    if( buffer[ j + 1] == 0xC0 )
                        printf("eax,eax" );
                    else if( buffer[ j + 1] == 0xDB )
                        printf("ebx,ebx" );
                    printf( "\n" );
                    j++;
                }
                else if( buffer[ j ] == 0x83 )
                {
                    printf( "cmp" );
                    if( buffer[ j + 1 ] == 0xFB )
                        printf( " ebx, %x", buffer[ j + 2 ] );
                    else if( buffer[ j + 1 ] == 0xF8 )
                        printf( " eax, %x", buffer[ j + 2 ] );
                    printf( "\n" );
                    j += 2;
                }
                else if( buffer[ j ] == 0x85 )
                {
                    printf( "test " );
                    if( buffer[ j + 1 ] == 0xDB )
                        printf( "ebx,ebx" );
                    else if( buffer[ j + 1] == 0xC0 )
                        printf("eax,eax" );
                    printf( "\n" );
                    j++;
                }
                else if( buffer[ j ] == 0x74 )
                {
                    printf( "je short %x\n", preferredBase + j + 2 + buffer[ j + 1 ] );
                    j++;
                }
                else if( buffer[ j ] == 0x53 )
                {
                    printf( "push ebx\n" );
                }
                else if( buffer[ j ] == 0xB8 )
                {
                    printf("mov eax,%x\n", buffer[ j + 1 ] );
                    j+=4;
                }
                else if( buffer[ j ] == 0xBB )
                {
                    printf("mov ebx %x\n", buffer[ j + 1 ] );
                    j+=4;
                }
                else if( buffer[ j ] == 0x50 )
                {
                    printf("push eax\n" );
                }
                else if( buffer[ j ] == 0x58 )
                {
                    printf("pop eax\n" );
                }
                else if( buffer[ j ] == 0x6A )
                {
                    printf( "push %d\n", buffer[ j + 1 ] );
                    j++;
                }
                else if( buffer[ j ] == 0x5B )
                {
                    printf( "pop ebx\n" );
                }
                else if( buffer[ j ] == 0xE8 )
                {
                    printf( "call %x%x%x%x\n", buffer[ j + 1 ], buffer[ j + 2 ], buffer[ j + 3 ], buffer[ j + 4 ] );
                    j+=4;
                }
                else if( buffer[ j ] == 0xFF && buffer[ j + 1 ] == 0x25 )
                {
                    printf( "jmp dword ptr ds:[%x%x%x%x]\n", buffer[ j + 2 ], buffer[ j + 3], buffer[ j + 4 ], buffer[ j + 5 ] );
                    j+=5;
                }
                else
                    printf( "db %x\n", buffer[ j ] );
            }

            printf("----------------------------------------------------------------\n" );
            
            delete[] buffer;

            sectionHeaderBase += sizeof( IMAGE_SECTION_HEADER );
        }

        UnmapViewOfFile( base );
        CloseHandle( hFileMappingObject );
        CloseHandle( hFile );
    }

    getchar();

    return 0;
}

Hope you had a fun time - it does make you appreciate the dis-assemblers currently out so much more, no?

Until next time,
<3 attilathedud

References:
http://win32assembly.online.fr/pe-tut1.html
http://win32assembly.online.fr/pe-tut2.html
http://win32assembly.online.fr/pe-tut3.html
http://win32assembly.online.fr/pe-tut4.html
http://win32assembly.online.fr/pe-tut5.html
http://caml.inria.fr/pub/docs/oreilly-book/html/book-ora065.html

Due to file restriction sizes, the version attached on this site is without the images.

Attached Files




#33576 Trainer Request: Robot Wars Extreme Destruction

Posted by KEMiCZA on 15 May 2011 - 03:09 PM

I'll take a look.