Saturday, 30 November 2013

Detoruing x64 System Call Stub: X86SwitchTo64BitMode


It's been a while since I posted anything, anyway now that I am here I am going to be giving a detour for: X86SwitchTo64BitMode.

X86SwthTo64BitMode is the deepest call before everything switches into 64 bit mode and other inaccessible DLL files. Additionally X86SwitchTo64BitMode can be detoured fairly easily unlike KiFastSystemCall, a usual JMP would do the job especially because we don't care if we overwrite instructions because we are not jumping back to the original instruction.

The Code is more or less pretty straightforward for any Windows savvy users.

Link: X86SwitchTo64BitMode.cpp

As said before, this code can be easily incorporated into a Global detour, additionally you may find this suitable to incorporate into your projects with credits to - Code Empire.


Wednesday, 13 November 2013

Security: Process Injection & detouring


I will be posting on how to inject into foreign processes then place a detour on specific API's, our example being MessageBoxA however this technique can be adapted to any API detour with slight change. Some useful API calls to detour would be:
- NtOpenProcess
- NtTerminateProcess
- NtQueryDirectoryFile
- NtQuerySystemInformation 

more exotic API's include:

- TurboDispatchJumpAddressStart
- KiFastSystemCall
- X86SwitchTo64BitMode
- Wow64SystemServiceEx
- CpuSimulate

As you may guess, there is again both malicious and positive purposes. It is always beneficial to understand these things, especially in case these task raise up.

The injection is modified slightly from the Mozilla Firefox post which was posted last month. I could have placed a detour directly on the API address using few easy workarounds however I simply created a entire thread which places the detour, just to show it as a Proof-Of-Concept code to newbie security analysts & security developers.

The code follows:

  • Open the process with flag set to PROCESS_ALL_ACCESS however this can be reduced to bare minimum
  • Create and fill a _CODE structure ready to be added as a parameter to our injected thread
  • Then allocate all the space needed for the processes which include - Thread, Parameter
  • Create the remote thread
The explanation above shows the procedure to inject code into foreign process but the thread performs something more or less the most important part of the program:
  • Use the _CODE structure then store the appropriate members in specific typedefs to be called
  • Calls MessageBoxA with parameters being set to those given from the _CODE structure
  • Finally patches MessageBoxA to redirect the control to a callback 
  • Additionally the thread also patches the callback to ensure the callback returns the control back to original 
Now I will elaborate on the job of the callback:
  • The callback reinstates the lost bytes of the original instructions 
  • Jumps back to original MessageBoxA  
  • Returns 
You would get a good idea on how it works, however for those who still have no clue here is the download:

Until Next Time,

Thursday, 31 October 2013

Security: Social Engineering using UAC


Today, we will be exploiting the UAC Architecture - for developers wanting to become savvy on Windows, UAC is a abbreviation for User Account Control it is designed to allow individual processes to run in various Account Levels, additionally it protects the host from malicious software from gaining higher privileges without consent.
However Microsoft while developing UAC, and perform bug checks they forgot to notice Windows Command Preprocessor, functionality which defeats the purpose of Command Prompt.

As you know Windows Command Preprocessor has extremely rich parameter usage, which can be exploited in order to run a different program but UAC shows that the program is trusted:

*** The Username is blurred out, for obvious reasons ***

 The above UAC is the default UAC which pops up, this UAC is also set to the highest level to show it works effectively on the most harshest\secure PC's.
While this look completely trustable, you can see the real-trick when we click on the "Show details" expander control located bottom-left.
Once we click that the true identity is shown:

As you may observed, only when we press "Show details" expander control located bottom-left we can see the true identity of this UAC alert, however majority of the time 80-90% of the Users tend to never click on show details especially if the UAC has a trusted software wanting elevation.

To show even more, if we press publishers, it shows Certificate is OK, many may think this is about the Malware but the certificate is CMD.exe's therefore we have performed Social Engineering Attack.
We can easily perform this via a simple call to ShellExecuteExA\W, with the lpVerb set to - "runas" and lpFile set to - location of Cmd.exe however to start our Malware as well we can use lpParameters to elevate our Malware like so - /c start %Malware Path%.
This technique will not only reduce huge amount of code and effort but is useful when deploying untrusted applications in the sense that it does not contain any digital signatures.
Source code:

As you may see I have not included entire source file such as headers as those can be added upon easily.


UAC is pretty secure itself such as prevents buffer overflows (to a certain extent of course) and such similar attacks however, it need more stricter settings by maybe show a label suggesting a parameter is added or showing additional details by default rather than giving user a choice.

As for the current UAC, it can still be "hacked" via a code injection into UAC when it pops up to hide the "show details" tab  therefore evading prying eyes even further.

Stay Tuned,

Monday, 28 October 2013

Security: Blocking DLL Injections


Today - we will be discussing about Injections and prevention of Injections, malware in generally notorious for stealing vital information from Softwares - This causes concern for most Developers working in the Security and Financial Industry as in these field, safeguarding customer data is a very important goal.

Malware(s) perform DLL Injection into the target, the DLL loaded would be a malicious DLL which would steal personal information, the generic malware authors tend to use LoadLibrary and WriteProcessMemory in a combination in order to successfully load a DLL into the Processes memory space, although this many Security Developers and Financial Developers simply detour LoadLibrary and expect the Application to be safe, however a simple call to a lower level function would bypass your layered protection, thus breaching the security.
However if we wanted to block the injection, without ourselves injection then performing a system-wide patch - we can use a LDR function which is function used to load DLL onto our Application, placing a nasty detour on that function would completely safeguard us against many User-Level Malware including Citadel.

The "magic" function is called LdrLoadDll, after we detour this function - we will be able to block many Injector(s) example  - WinInject.

Let's Get Coding, First we will start by the function responsible for patching LdrLoadDll:

As you see, we are not doing any special detouring method but the usual jmp method, I did not re-protect the memory address space as you can do anything more like add your own code\replace code.

Next we will be covering the Callback, the callback itself is more or less, simple filtering mechanism however you can customize the mechanism to your own liking:

As you may have noticed the callback simply blocks all DLL locations\names in the C: drive however if the DLL's exist in System32, we cannot block it. All this does is allow trusted DLL to load, but this can be bypassed if a Malware sets its DLL in System32:

The code above is quite straightforward so, not much to explain apart from the LdrAddress variable is a global variable therefore, you cannot see the variable.
These are only real\important piece of code as you may know as all main does is call the Install detour functions and thats all - from then on the callback handles it all.

The code, as I could not fit it into a single screenshot, I am going to give the code in a *.cpp file:

Next, time I will be covering how to block Code\Process Injections.

Until Next Time,

Saturday, 26 October 2013

Kernel Drivers: Hiding True Identity


Today I will be discussing a method to hide true identity of a Kernel Mode Driver. This method is not well known but exploited by ZeroAccess Trojan quite well. I will add my own "unique" touch to it in order to make it more effective. This is not for malicious purposes but for security researchers.
This trick does not only useful for Security Developer(s) but also may be somewhat use to Driver Developer especially because to test & run drivers quickly rather than getting it test signed or disabling Driver Signature Enforcement.

***NOTE*** This blog\post is only a method and does not involve code. 

ZeroAccess Trojan, a notorious trojan responsible for thousands of infection world wide, uses various methods in order to stay resilient and it does by placing Kernel detours on the system using a driver (*.SYS) . Normally, all we need to do is startup the driver using Windows API on x86 systems as there is no sort of protection which guards the Kernel except maybe few AV which again can be bypassed using custom load technique, however this trick would fail miserably on x64 Systems as PatchGuard protects the Kernel from loading "rouge" drivers, but circumventing this is pretty much easy.

If you analyse ZeroAccess Trojan you will see that on x86 systems it get's a driver and copies it to the ZeroAccess Trojan's installation directory then replaces the bytes\information with it's own rootkit code, this is a excellent technique - but this technique is never needed to load the driver on x86 as it has no protection on the kernel but just as a safety precaution to avoid prying eyes of the host user. This same method can be used to bypass patch guard on but to maintain more safety, you need to add garbage code EOF as if you write something on the EOF nothing can be destroyed or corrupted therefore it can bypass few run-time checks and in addition you can add a lot of NOPS on front of your driver in order to confuse and reduce the detection ratio. Then before hand feel free to use a crypter on it inorder to encrypt the file and DON'T ever pack the Driver as most AV solutions use their heuristic behaviour detection in order to detect this as most Malware tend to pack it. If you really want to pack it do not use famous packers such as UPX as these are mostly used by Malware authors.

Next, if your application is in sandbox and to bypass the sandbox, you can perform a far jump into 0x33:[$+5], this would simply change the code next code's into 0x64 code then re-form a far jump into 0x23:[$+5], this would change the following code back into 0x86. I realised the potential for this trick when trying to test a anti-debug trick I created, I tested this on VirusTotal and it is unable to scan\emulate the file in order to give me results as multi code-segment changes messed up the most AV sandboxes and Online File Scanning service. This is one of the brilliant tricks to implement in order to bypass most if not all proactives.

To conclude, there is many many more methods to bypass these security solutions and other protection software.
Keep Looking

Until Next Time,

Wednesday, 23 October 2013

Kernel Driver: SYSENTER detour


Today we will be covering Kernel Mode detouring. Kernel Mode detouring is extremely powerful, most AV solutions operate on Kernel Mode.
The reason they operate on Kernel Mode, is solely due to the power and control they will posses, for example we can create a patch which will make sure that if a "backdoor" password is used on login or UAC, it accepts it. 

Back to topic...Using Kernel Mode driver is powerful as stated previously but can leave devastating effects if the Driver failed to work properly, therefore test it on VM before even attempting to run code on original machine as our machines could be different. 

Now we will dive into the realm of the code and theory

SYSENTER is the target we will be detouring, SYSENTER is a intel provided opcode to transform\jump into kernel mode, in addition detouring the opcode is detouring in the lowest level of Windows Kernel. As any decent reverse engineer would have discovered that SYSENTER opcode is only available in x86 bit Windows OS. 
If one wishes to detour deeper, s\he can detour interrupts, although this is\should be covered in upcoming tutorials. 

As Kernel mode by design allows us to detour these in fairly short amount of code - 

it only takes few lines of Assembly x86 :

- Grab current System Call handler from the 0x176 SYSENTER_MSR
- Read the value of IA32_SYSENTER_EIP 
- Save real SYSENTER address  
- Replace SYSENTER address with our detour callback
- Write the new\callback address to IA32_SYSENTER_EIP 

Lets get coding...

We will start defining the Driver Entry ( ***NOTE*** This also contains detour code):

The actual unload routine is not really anything special and a usual routine you normally see. 
As for the remaining code I am not really going to explain it as it more or less straightforward with the comments. It makes no sense for me to explain it all over again.

Now I will show the SysenterCallback "function":

To be honest, I do not really need to show example of how to filter content out using assembly instructions such as cmp and other similar instructions. Note - Here I was too lazy to add a void after _declspec(naked) as it was a test\code which worked and was just to show you guys. It is always a good programming practices to specify the data type. 

The Entire Code  (Comments Removed) : 

This is all there to, detouring the deepest level of Windows Kernel. You can use this code for variety of purposes from Malware Research, to Anti-Virus Programming or Kernel Diagnostic tools. 

This code works on pretty all Windows NT Operating Systems, with minor adjustment to the code. 
After you have compiled this properly and has been successful, to run the code follow this tutorial on CodeProject :

Until Next Time,

Monday, 14 October 2013

Code Injection into Mozilla Firefox


To follow, the previous posts (Injections & Security) - I developed a CODE injection module which is able to consistently inject into Mozilla Firefox. Instead of developing a DLL Injection module, I developed a Code Injection module. As Software Engineers in top businesses say - "Code Should be left to the bare minimum", I followed this "tradition" and developed a single application to inject without external file(s).

For those who never heard about Code Injection, I am going to explain what code injection is and it's uses in both commercial softwares, and Security Exploitation Software.
As there are several methods to inject into a application - PE Injection, DLL Injection etc. Code Injection is one of the rarest, first being obviously PE Injection ( Due to difficulty of the long-windedness of the procedure). Code Injection is a method in which we execute our own code\instructions inside a different processes memory space.

Code Injection, unlike DLL Injection, takes a little bit more hard work:

- Calculating injected thread's size
- Exporting single functions from libraries
- Correct Code Placement among Source
- Thread\Code Objects must be all correctly calculated and allocated.
- Manual Thread synchronization such as exporting other functions addresses

All in all, Code Injection is all maintained manually and checked prior to compilation; Code Injection is also infamous for amount of bugs which can be extremely hard and difficult to locate and remove.

Nevertheless, it has unique uses both for commercial uses and for Security Exploitation software, for commercial application development it can be used in various different scenarios:

- To reduce\minimize the size of the code inside a Project as we do not need to develop a DLL and Application.
- To add security watchdog on the software\application
- To add new plugins, without the Developers having *much knowledge about Firefox SDK
- To perform\check system maximum performance

These are few uses of Code Injection in commercial application development although there are way...way more uses in commercial application development, but I'll leave that to your imagination. As for Security Exploitation software, these include:

- To steal and grab vital form data as they are sent.
- To check for signs of Malware present in the system.
- To unhook and prevent Malware from entering vital processes memory space
- To bypass AV firewall solutions
- Bypassing AV proactive file scanning as we are not dropping any malicious DLL files, which may get flagged by local Anti-Virus solution.

Again, this shows small amount of examples in which Code Injection can come into use - but I'll again, leave this to your imagination.

Before you dwell deep into examining the source code provided, I will break down the steps I followed in order to achieve a perfect code injection into Mozilla Firefox:

  • Create firefox process with the dwCreationFlag ( 6th Parameter in CreateProcess) set to CREATE_SUSPENDED 
  • As I inherited important information of the process from the PROCESS_INFORMATION structure such as - Main Thread, Complete Access Process Handle, Main Thread ID, Process ID. 
  • Then I initialized the parameter structure and later filled in all it's members with valid data 
  • Next I calculated and allocated memory and wrote the thread's memory inside the allocation unit of the injected thread inside the process memory space
  • After I did the same for the parameters 
  • Lastly I created the remote thread inside the foreign process memory space.   

***Note*** I did not do much error checking as I expected the application to work and it was not part of any projects nor large research but in fact a small test-run I did to check if the security of Mozilla Firefox was good. 

The Mozilla Firefox version this is tested on is the latest for till this day (14/10/2013) version: 24.0 
I expect this code to work on older versions & MAYBE future versions. 


This blog post has become way too long than expected, so let me wrap it up and provide you with the code:

Hope you learned something new!

Sunday, 13 October 2013

DLL Injection into Google Chrome


Today, I wanted to share a injection method into Chromium (Google Chrome) browser. Google Chrome is known for it's Security - which protects it's End-Users from Malware, but unfortunately Google Chrome missed out the most simplest DLL injection method - a basic thread creation using CreateRemoteThread, this should be obvious to Google Chrome Developers as the it is commonly used by Malware, on contrary to what the developers said... "Sandbox" is not safe as we were informed.

There are very powerful uses if a DLL is executed inside memory\process space of Google Chrome, these include:

- Bypassing AV firewall solutions, as Google Chrome is by default enabled to perform network activity
- To steal and to formgrab vital pieces of Data such as Login details for Email accounts
- To prevent downloads of Security Utilities such as AV solutions.

These are some negative impacts but these are the positive aspects to use such a DLL injection:

- To create hotkeys\ personalisation applications without using Chromium SDK
- To block Malicious Threats
- Use it to create rich P2P\Network Applications for End-Users, without needing a Internet Allowed Certification
-  Remove Malware's detours on the Google Chrome

Before, I give the code for the DLL injection, do note that:

- This DLL Injection method has been tested on Google Chrome Version: 29.0.1547.62
- Using this method to perform Code Injection can crash the application or can result in unexpected behaviour of injected thread.

To protect from this injection method follow these steps:

- Create a DLL, which detours LoadLibraryA & LoadLibraryW
- In the detour callback simply return 0; which means if this method was called by Malware it would fails as our callback does nothing with this functions
- Inject a DLL into Google Chrome, to inject just re-follow this method

Do keep in mind if LoadLibraryA\W is detoured and returns 0, it would mean all Google Chrome LoadLibrary calls would fail as well, so make sure to implement a some type of identification, to ensure that you know if Google Chrome called it or a foreign process.

Once injected other 3rd Party Malware\Tools cannot inject into this using this method.

Detouring x86 System Call stub - KiFastSystemCall


Today, this blog is not much technical\tutorial but a snippet of detouring KiFastSystemCall.

KiFastSystemCall is the lowest level API available in Windows Application Level Layer (Ring3), all application' calls pass from KiFastSystemCall, KiFastSystemCall redirects all those controls onto the Windows Kernel via a instruction called sysenter.
As KiFastSystemCall is lowest level API available in Usermode layer, detouring that means we can subvert objects such as - Processes, Files, Network Connections and everything.
This detour can be used as a Anti-Malware scheme as even the most notable malware such as ZeuS, SpyEye, Citadel do not detour this low, so they become completely visible to us. We can even block some of their functionality such as Web injects and such.

As the code is too big to be in a single screenshot. I put it for download in MediaFire:

Download Link:

This detour does nothing special, but if you have a idea in mind - Usermode Ring3 AV, System Call Analyser etc. Feel free to incorporate this into your Software\Application. This detour is not global although if you perform Code Injection into other processes this has the abillity to become System-Wide, but as said before this lies in your hands.

For those who have x64 bit PC's do be aware that this code will not work as KiFastSystemCall is not the System Call Stub for x64. I am going to be posting the System Call Stub detour for x64 bit PC's - X86SwitchTo64BitMode.


Saturday, 5 October 2013

How to undetour NtOpenProcess


This is going to be a pretty small blog, today we will be discussing on how to undetour functions - mostly NT (Kernel-Related Functions), undetouring is a pretty simple objective to follow. The steps to follow in order to undetour NT functions.

We will be using NtOpenProcess as a example - this is the most common function to be detoured by various Malware & security utilities running in usermode (Ring3).
We will not be using kernel-mode drivers or such fancy equipment - just a usual application (.exe) but with tricks and techniques.

Now, the start of NtOpenProcess is more or less easy to guess the first few bytes:

mov eax, 23
xor ecx,ecx
lea edx, DWORD PTR SS:[esp+4]

If the function has been detoured this is how the first few bytes would look:

lea edx, DWORD PTR SS:[esp+4]

This means the 1st and 2nd instructions are overwritten as the size of the jump is 5 bytes, so to unhook this function all we need to do is replace the jmp with the overwritten instructions. The technique is same as detouring but patching different opcodes.

I will first discuss the steps needed to implement a "Anti-Rootkit" software:

  • Grab the Address of target function, in our case it is NtOpenProcess 
  • Compare if the prologue contains jmps
  • If so unprotect the prologue of the target function
  • patch the original instructions\opcodes into original spaces
  • re-protect the prologue of the target function 
We will grab the Address of the target function via calling GetProcAddress to grab the address of sleep, then save the address onto a LPVOID then to compare it we will typecast the address into a byte and check. If so we will use VirtualProtect to unprotect the memory region\layer then patch the entire original instructions which have been overwritten. Then re-protect it wil VirtualProtect .

First we will grab the address of NtOpenProcess:

Now we will use compare and see if the prologue contains tell-tale signs of any detour being placed:

Now we will unprotect the prologue of the function:

Now use the hot-patching\detouring method in order to patch undetour code onto function:

All we are doing now is re-protect it back to it's original format:

Now we have successfully undetoured the function, the code above were all snippets so this is the whole code to successfully undetour NtOpenProcess without using kernel-mode drivers, all in all we did a simpler job. Complete Code:

 This code would unhook NtOpenProcess without much trouble or problem, however this could fail on other Windows (apart from 7 x64) as I have tested this code on only Windows 7 x64. 
Anyway in my conclusion, I want to say that this code itself is not very fool-proof, as if a Malware or Sandbox detoured GetProcAddress or equivalent on a lower level, and blocked or filtered you call it would be disastrous, mainly being they could give you a wrong address. 

If this is the case why not call KiFastSystemCall or X86SwitchTo64BitMode directly by moving addresses into eax, and moving parameters on to esp. This would be a better idea as not many malwares detour vital system call stubs, or on x64 you can try perform a code segment change and directly call Wow64ServicesEx to bypass this or detour this it takes a lot of work so not many malwares will be able to protect themselves from un-hooking. 

Anyway, it is getting too long so lets wrap things quickly - If you understand how we unhooked NtOpenProcess, you can unhook all functions using a little bit logic and debugging. 

Thanks! Please Comment and Share - Hope You enjoyed and learned.

Friday, 4 October 2013

C# and VB IDE under development


My first post, anyway I started a project to build a C# and VB IDE and COMPILER, but I forgot to continue it as I was busy exploring other topics, therefore my project could not be completed although, I found it in my HDD but it was not very interesting so I recreated this time it is complete.

The features it has is:

  • Compiling
  • Compiling-Running
  • Saving Source File's
  • Syntax Highlighting
  • Target Language (C# - VB - Batch)
  • Fantastic UI (Metro Style)
The IDE was programmed in WPF(.NET) along with C# as back-end file. Uses .NET 4.5 download it from Microsoft Website for FREE!

Few Pictures of the IDE - 

These are few pictures of the IDE, it compiles - it run's and it compiles.

IDE is dubbed as - Terminus CodeCompiler .NET 

Currently I am developing a Native CodeCompiler - compiles Assembly both x86 and x64.

Download Link for the IDE is: