Mittwoch, 15. April 2015

[C# / 1.12.1 WoW] Render Disabler

Today I found an old tool I programmed for a friend some time ago. It can disable the rendering of the environment for multiple 1.12.1 WoW processes completely:

Source + binary version will be posted in the evening today.

Update: https://github.com/Zz9uk3/RenderDisabler

Donnerstag, 5. März 2015

[Tools] How to use IRC

If you are also active inside the WoW emulation scene you may already noticed that a lot of the communication is handled over IRC. However most people tend to use some kind of webchat instead of really trying to get into it and possible clients.

There are dozen clients but non as good as Hexchat (https://hexchat.github.io/downloads.html).
Download the for your system suitable file and install it:


Start HexChat.exe and wait for the window to show up.
Incase of HexChat being launched for the first time you will end up seeing the Network List.

In this example we will connect to the Kronos IRC channel which is hosted on the Mibbit network.
Obtaining the connection informations can be a bit annoying for some IRC networks however most of the time you do good hitting google with "XXX connection guide" (XXX is Mibbit in this case):


Now we can proceed adding the connection details in HexChat:
Go to the Network List window
Click Add and change "New Network" to a more fitting name like "Mibbit - Kronos"
Highlight the new network by clicking on it and hit Edit

The server format is domain/port 
If we are using SSL we put a + infront of the port:

 

The Connect Commands offers the possibility to specify commands which will be executed after connecting to the server. Many IRC networks got a registration system in place where you register and auth with a bot user named NickServ. Using this tab you can for example auth yourself everytime you connect to the network.
A little explanation on how to register a nickname on mibbit can be found here.

After setting everything up HexChat should connect properly:



Staying in IRC even after closing HexChat

IRC cant be compared to messengers like Skype where you can for example send messages to someone being offline. You hold your nickname as long as you are online. As soon as you disconnect the nickname will be free again for use  and someone else can connect under that name.
To avoid that someone else use your nickname you can register it. Depending on the network the person connecting with your registered nickname will be force renamed or will keep the name until you auth with your nickname.

Also there are bouncers. Those are programs running on a server keeping your nickname connected to the network 24/7. Imagine a bouncer as a proxy. You give HexChat the details of your bnc and it will connect through it to the network.

Final words

IRC looks complicated to those who never used it before and one may ask why we use such a system incase of Skype but once you made your first steps you will love it.
As someone who is interested in WoW development I can easily stay in touch with all projects I am interested in without adding thousand of contacts to some messenger:


[C#] 1.12.1 Bot source code

I decided to release the source code of an old WoW Bot which is based on injecting Assembly into the WoW process: https://github.com/Zz9uk3/CorthezzWoWBot

Enjoy! :)

Donnerstag, 15. Januar 2015

[C#] Accessing Form Controls from another thread / class

While working on a new advertising tool I thought a progressbar indicating how many players stil need to be whispered would be pretty cool:
However one will face problems directly accessing the progressbar from another thread since our thread can collide with the thread which created the progressbar (the UI thread).

To avoid those crashes C# offers a method Invoke which requests another thread to execute code through a delegate (read more).

Speaking in code:

First of all we create a delegate which takes an int as parameter:

 private delegate void updatePbDelegate(int percentage);  

Following that step we create a function which will be called by the other thread:

 public void updatePb(int percentage)  
 {  
      if (this.InvokeRequired)  
      {  
           updatePbDelegate set = new updatePbDelegate(updatePb);  
           this.Invoke(set, new object[] { percentage });  
      }  
      else  
      {  
           pbSender.Value = percentage;  
      }  
 }  

InvokeRequired compares the callers thread with the thread that created the GUI (read more).
If the call comes from another thread a delegate instance pointing to updatePb will be created and passed to Invoke which will then proceed and call updatePb from the UI thread. This time InvokeRequired will return false and the value of the progressbar will be adjusted.

Last but not least we need to pass our Form instance to the thread which will look like this:

 public partial class Form1 : Form  
 {  
      public Form1()  
      {  
           InitializeComponent();  
           Sender.Start(this);  
      }  
      private delegate void updatePbDelegate(int percentage);  
      public void updatePb(int percentage)  
      {  
           if (this.InvokeRequired)  
           {  
                updatePbDelegate set = new updatePbDelegate(updatePb);  
                this.Invoke(set, new object[] { percentage });  
           }  
           else  
           {  
                pbSender.Value = percentage;  
           }  
      }  
 }  
 internal static class Sender  
 {  
      private static Thread thrSender;  
      private static Form1 formAccess;  
      internal static void Start(Form1 parForm)  
      {  
           formAccess = parForm;  
           thrSender = new Thread(Pulse);  
           thrSender.IsBackground = true;  
           thrSender.Start();  
      }  
      private static void Pulse()  
      {  
           formAccess.updatePb(100);  
      }  
 }  

Donnerstag, 11. Dezember 2014

[C#] Switch-case based Console Menu

In my opinion its annoying validating the console input of the user. This little snippet will offer a menu where the user can navigate between the possible options with the arrow keys (up and down) and select one pressing enter:


The function takes a string which will be printed on top of the options (a description?) and a string list containing the selectable options. the returned int will hold the index of the selected item.

printMenu function:
 private static int printMenu(string parHead, List<string> parOptions)  
 {  
      Console.WriteLine(parHead);  
      int count = 0;  
      bool firstRun = true;  
      bool bEnd = false;  
      while (true)  
      {  
           if (!firstRun)  
           {  
                switch (Console.ReadKey(true).Key)  
                {  
                     case ConsoleKey.UpArrow:  
                          count = (count - 1) % parOptions.Count;  
                          if (count < 0)  
                          {  
                               count = parOptions.Count - 1;  
                          }  
                          break;  
                     case ConsoleKey.DownArrow:  
                          count = (count + 1) % parOptions.Count;  
                          break;  
                     case ConsoleKey.Enter:  
                          bEnd = true;  
                          break;  
                }  
                ClearConsoleLines(parOptions.Count);  
           }  
           char select = ' ';  
           for (int i = 0; i < parOptions.Count; i++)  
           {  
                if (count == i)  
                {  
                     select = 'x';  
                }  
                else  
                {  
                     select = ' ';  
                }  
                Console.WriteLine(parOptions[i] + new string('\t', 1) + "[" + select + "]");  
           }  
           firstRun = false;  
           if (bEnd) break;  
      }  
      return count;  
 }  

ClearConsoleLines function:
 public static void ClearConsoleLines(int parLines)  
 {  
      for (int i = 0; i < parLines; i++)  
      {  
           Console.SetCursorPosition(0, Console.CursorTop - 1);  
           int currentLineCursor = Console.CursorTop;  
           Console.SetCursorPosition(0, Console.CursorTop);  
           Console.Write(new string(' ', Console.WindowWidth));  
           Console.SetCursorPosition(0, currentLineCursor);  
      }  
 }  

Example usage:
 List<string> listExample = new List<string>();  
 listExample.Add("option1");  
 listExample.Add("option2");  
 listExample.Add("option3");  
 listExample.Add("option4");  
 listExample.Add("option5");  
 listExample.Add("option6");  
 listExample.Add("option7");  
 int res = printMenu("Select one:", listExample);  
 Console.WriteLine("\n" + listExample[res] + "\n");  

Dienstag, 9. Dezember 2014

[Reversing / 1.12.1 WoW] Detouring functions

Some time passed and I finally convinced myself to work on the blog again. Using this post I want to continue with the tutorial series having the goal to write a bot for vanilla WoW.

Some Notes:

This time we will focus on injecting assembler code into the WoW executable. Before I start I want to say that I am not the super b reverser and you may find mistakes here and there. Thanks in advance for any hint regarding possible mistakes. If you have problems understanding certain parts I would be happy for a quick message.

Whats the deal about injectin ASM?

If we write bots we have multiple ways to interact with the client. For example we want to target a mob:
We can simulate a tab keypress which will make the client target an attackable mob in line of sight or we can call the function which handles the targeting.

This is just a very basic example but the power of injecting code goes much further: We can start sending packets, call click2move functions, we can even manipulate functions to do things which they arent supposed to do normally.

How does it work?

When we launch WoW the executable is copied into the RAM. The bytes are divided into different segments. In the below example I used IDA to display the segment boundaries of the 1.12.1 WoW executable:


Since Segments arent any important for us at the moment I dont go into detail however you can read up a bit here and there if you like.

Every byte of our target process is accessable via a virtual address (VAS) which can be used in combinisation with a process handle to read from or write to it:

 byte[] res = new byte[6];  
 IntPtr countOfBytesRead = IntPtr.Zero;  
 ReadProcessMemory(WoW.Handle, (IntPtr)0x00837C04, res, 6, out countOfBytesRead);   

This little snippet will call ReadProcessMemory with the handle to our current WoW process aswell the virtual address 0x00837C04. The bytes stored at 0x00837C04 are representing the version string.
Since one ASCII-character takes 1 byte and "1.12.1" consists of 6 characters we have to read 6 bytes:

1.12.1 -> 0x31 0x2e 0x31 0x32 0x2e 0x31
  • 00837C04 holding 0x31
  • 00837C05 holding 0x2e
  • 00837C05 holding 0x31
  • ...
Beside from bytes holding values we also got bytes which are instructions executed by the CPU:


Here we see a function of WoW which we will modify to our needs later. The asm instructions seen at the right of the picture represent the bytes on the left. "PUSH ESI" represents 0x56 for example.

Like in any other programming languages the instructions will be executed one by one from top to the bottom. It looks very complicated at the beginning if you never touched ASM before but playing around with OllyDBG, asking google and reading a few sources will get you going pretty fast (thats atleast what I did).

To modify those instructions there are two solutions I used so far:
  1. Write the bytes for the instructions using WriteProcessMemory
  2. Use a library which accepts ASM instructions, translates them into the corresponding bytes and write them to memory
For the moment I prefer the second method.

About registers and the stack

Before we start you should read up a bit about the stack and registers:


Registers (shown on the upper right) can store 4 byte each. To move a value into them we will use the mov instruction:

 mov eax, 1  ; eax holds the value 1 now

The stack are a bunch of 4 byte values. Using the pop instruction we can move the very top value into a register. Using the push value we can push a register to the top of the stack. Imagine it like a bunch of cards where we can put a new one to the top aswell withdraw the one at the top (Understanding the stack).

Its important that we leave the stack aswell the registers in the state they was before our first injected instruction is executed. Otherwise we have the risk to mess up and crash the process (WoW expects a pointer to a struct in eax and we moved a zero in it without restoring the old eax value for example).

Detouring

To execute our own instruction we have to take a few steps:
  1. Find a function which is constantly called by WoW (for example directX's EndScene function which produces the image we see while playing -> more info)
  2. Allocate space for our instructions (note down the address of our allocated space)
  3. Inject our instructions at the previously allocated space
  4. Overwrite the first few instruction of EndScene to make a jump to our space
  5. Execute the overwritten instructions followed by our own code
  6. Jump back to EndScene
The whole process a bit simplified:


Instructions stored at address 61 to 66 are injected. Instructions from address 1 to 4 represent a function of WoW which we modify.

Finding EndScene

The EndScene is located at a different address every restart. In conclusion we need to find a way to obtain it each time automatically. I will describe the method I used. Thanks to Namreeb we know that EndScene is called at 0x5A17B6 (give him some rep if you can :p)

  1. So we fire up OllyDBG and attach it to a WoW instance.
  2. Hitting 'CTRL+G' we can jump to any valid address inside the attached process (which is 0x5A17B6 in our case)
  3. As we can see the instruction calling EndScene is "CALL DWORD PTR DS:[ECX+A8]". The logic conclusion is that the address to EndScene is stored at ECX+A8
  4. To retrieve the address we will overwrite the call to endscene with a jmp
  5. Grab the content of ECX+A8
  6. Execute the call we have overwritten
  7. Restore everything to its default state

Since I dont feel like explaining code step by step I wrote a well documentated sample program which will grab the address EndScene is stored at:


Also noteworthy: A jmp takes 5 bytes. The instruction we overwrite in the sample tool takes 6 bytes. After executing our detour we cannot just jump back 5 bytes further and execute a instruction we previously "broke" by modifying parts of it. We need to make sure that we jump to the next full instruction.

If I tell you to start reading the word "hello" at the 3rd character you will end up reading "llo" being confused by what this unknown word should mean to you. I hope you see what I try to say with that :).

Edit from 2017: I sadly lost the source of this example and Filebeam went offline. Stupid me back then should have used GitHub over strange FileHosters :)




Donnerstag, 13. November 2014

About Proxy PAC Systems and RegEx

Different proxy systems

When I browse the web I got a few factors which are important to me:
  1. My traffic should be encrypted
  2. No webserver should see my real IP
  3. I dont want any company to collect data about my surf behaviour
  4. I dont want to be restricted from content only avaible to certain countrys
Today nearly every application has a bunch of options dedicated to routing the traffic over a proxy which makes the setup very easy:



Most tools offer us options for different proxy protocols including Socks, HTTPS aswell HTTP.
Having the possibility to set only one static proxy is a nice start but what are we supposed to do if we want to use different proxys without manually switching them each time?

The answer is pretty easy: PAC (Proxy auto-config)
Proxy auto-config is a proxy mode which evaluates the site we are visiting and chooses a proxy depending on user specified conditions.
The evaluation process is defined within a .pac file which we point our browser to. The code is written in JavaScript:

 function FindProxyForURL(url, host)  
 {  
      return "DIRECT";  
 }  



Everytime our browser is connecting to a page it will call the FindProxyForURL with the URL aswell the host as parameters. Lets make an example:
1. We are visiting http://www.youtube.com/watch?v=Mh_cLN66zHA

2. Our browser will call FindProxyForURL with the following parameters:
URL: http://www.youtube.com/watch?v=Mh_cLN66zHA
Host: www.youtube.com

3. The return value of FindProxyForURL will define how we connect to the page: 
"DIRECT" -> make a direct connection
"PROXY 127.0.0.1:81" -> Connect over http proxy at 127.0.0.1:81
"SOCKS5 127.0.0.1:1028" -> Socks5 at 127.0.0.1:1028
etc.

4. Using the above script we will connect directly dont matter the URL or host. Later on I will show how to extend the script.

Creating an extended pac

If I visit YouTube my traffic is routed over an american server without any encryption since videos arent getting blocked because of copyright over there. Encryption isnt important since the information being transfered to youtube isnt sensitive and it would only slow down the connection.

For every other kind of connection I use an encrypted tunnel to a server located in the Netherlands since their internet policy is very tolerant.

1. Recognise a url which belongs to YouTube:

We could check if the url contains "youtube" but the result wouldnt be very accurate:
https://www.google.de/?gws_rd=ssl#q=youtube would be recognised as youtube for example.

Instead of just searching for a string we take advantage of regular expressions. A few useful links about RegEx:
http://en.wikipedia.org/wiki/Regular_expression
http://regexlib.com/CheatSheet.aspx
http://www.regexr.com/

Dont be intimidated by the first look. Its actually a good understandable topic. To give you a little push in the right direction we will define a pattern which finds youtube urls:

 ^https?:\/\/(www\.)?([^/]+\.)?youtube\.com  

^ represents the start of a string. In conclusion our string has to start with http
a ? after brackets or a single character states that the bracket content or the character can occur one time but dont need to.
Our string can begin with either:
  • http
  • https


backslashes (\) are used to escape characters which would have another meaning unescaped.
backslash-slash (\/) represents a slash (/) for example.
Going from that our matched string can be:

  • http://
  • https://
(www\.)? states that www. CAN occur one time but dont need to. Our possibilities:
  • http://
  • http://www.
([^\]+\.)?:
Like we previously learned ? means that the bracket content can occur up to one time.
[^\] represents any character but backslash (\).
The + after [^\] states that we can have one to unlimited characters which arent backslahes.
[^\]+ represents:
  • ...
  • a
  • aa
  • aaa
  • abc
  • ...
but it doesnt represent:
  • ...
  • \
  • a\
  • aa\
  • aaa\
  • ...
In conclusion: We can have up to one substring which includes unlimited characters that arent backslashes and ends on a dot (.).

A few possible matches for "^https?:\/\/(www\.)?([^/]+\.)?":
  • http://www.aaa.
  • https://www.a.
  • http://aaaaaa.
  • https://aa.
Remaining part of our RegEx is just youtube\.com which means that youtube.com has to follow. No rules here. Simple as that.

It might be a bit complicated at the first look however you can trial and error yourself through this topic using the previously linked RegEx cheat sheet aswell the RegEx tester. Every rule I used in my expression is also explained on the sheet (and yes I never used RegEx before so my expression might not be perfect).

Having explained a sample expression I continue defining two RegExp objects inside my pac:

 var youtubeRegEx = new RegExp("^https?:\/\/(www\.)?([^/]+\.)?youtube\.com", "i");  
 var ytStreamRegEx = new RegExp("^http:\/\/[^/]+\.googlevideo\.com", "i");  

The second parameter "i" makes the expression case insensitive (a = A).

2. Extend FindProxyForURL(url, host)


 function FindProxyForURL(url, host)  
 {  
      if (youtubeRegEx.test(url) || ytStreamRegEx.test(url))  
      {  
           alert("YT proxy for URL: " + url);  
           return "SOCKS5 X.X.X.X:1080";  
      }  
      return "SOCKS5 127.0.0.1:5555";  
 }  

test() is a function from RegExp objects taking a string parameter. If the expression can be found inside the given string (in our case the url) the function will return true:
If the current url belongs to youtube our browser will use the socks5 at X.X.X.X:1080 (the american proxy server)
Otherwise it will use my local SSL-Socks5 (replaceable with DIRECT for a direct connection).

3. Verify our pac-script

Debugging a pac script can be very annoying and isnt even possible in every browser. For SrWare Iron (or better said Chrome) you can do the following:

If you scroll up you will see that we call alert() inside the if brackets. This will give us some debug information:


Chromium related browsers will change the system proxy settings by default. You should get a proxy extension like "ProxySwitchy Sharp" or "Proxy Helper" so the changes are only applied to Chrome / SrWare Iron.