You must specify your application assembly name and version in the application’s <assemblyIdentity> tag. Additional attributes are optional.

How to Connect Your Application to the Manifest File

There are two ways to connect your application to the manifest file:

Place the manifest file in your application home directory. This requires the manifest file to have the same name as your application executable, with the “.manifest” suffix. For example, if your application executable is MyApp.exe, you must name the manifest MyApp.exe.manifest.

Embed the manifest in your application executable as a resource.

The second option involves a bit of work with project settings, and is described in the section below.

Deviare DLLs and database files should be placed in your application’s home directory or another searchable location (e.g: in the system path). Be aware that when you mix projects using Deviare with the Reg-Free COM mechanism with other projects using manual registration you may experience issues such as versioning problems. You can use the regsvr tool with the /U option to manually unregister Deviare.

Visual Studio C++ Project Setup Guide

To use Reg-Free COM Deviare in a C++ VS application, follow those steps:

Create one manifest file for each target platform as shown at the beginning of this article. Name them “RegFreeCOM_x86.manifest” and “RegFreeCOM_x64.manifest”. Copy those files to your source file directory.

Open your project settings, select the desired platform, go to “Manifest Tool >> Input and Output” and enter the filename in “Additional Manifest Files”. You can specify variables such as $(SolutionDir), $(ProjectDir) to modify the manifest path. Make sure the selected platform and manifest file platform match.

Do the same for the other platforms in your project,. In this case, the x64 platform:

DeviareCOM DLLs must be in the same directory as your executable. You can copy them manually; or use “Post-Build Event” in “Project Settings” to automate this step.

In the screenshot above, we show an example of how to use the “Command Line” field to copy Deviare DLLs and databases from a DLL directory within the solution directory ( $(SolutionDir) variable) to the output directory where the application executable is generated ( ($OutDir) variable).

Build your project and test your application.

C# Project Setup Guide

Important: Visual Studio uses VSHOST.EXE to improve debugging when you launch an application. As a result Visual Studio ignores your embedded manifest and COM components are not loaded properly. There are two workarounds: 1) execute your application outside Visual Studio or 2) uncheck “Enable the Visual Studio hosting process” in your project settings:

If you want to use a single custom application manifest in a C# project, it’s easy to access the project settings dialog and choose a manifest file:

However, unlike Visual Studio C++ projects it is not possible to configure multiple-platform projects to use one manifest for each platform in Visual Studio C# projects. The above dialog only sets up a global manifest for the application.

Since Deviare 32-bit and 64-bit are different COM DLLs, you need to use different manifests to load them:

Create manifest files as shown at the beginning of this article, one for each target platform. Name them “RegFreeCOM_x86.manifest” and “RegFreeCOM_x64.manifest”. Copy these files to your source file directory.

Use a text editor to open your C# project file (“.csproj” extensión). Look for the “PropertyGroup” tags. There is one “PropertyGroup” for each configuration and platform target pair.

With either VS closed or the project unloaded to allow modifications, you must insert the manifest declaration using the proper manifest file platform below the “<PropertyGroup …>” opening tag. If we have the RegFreeCOM_x86.manifest and RegFreeCOM_X64.manifest to use on the x86 and x64 builds, respectively, first, we’ll add the manifest declaration of the x86 build:

With the exception of Compuware, the leaders, New Relic and AppDynamics, are all newcomers. All the old established companies are excluded from the leader’s quadrant.

Gartner separates APM and analytics products, suggesting that the latter are mere complements. However, when paired with third-party applications, these analytics products are perfectly capable of replacing APM.

Our hypothesis is that the whole APM market will move into two specializations: analytics engines and agents for gathering performance metrics across different monitoring disciplines. Many new analytic or log management products are entering the market. Our new product ActivityLogger can send desktop and server metrics to an analytics product. In the example below, we send user experience metrics to Elasticsearch and display the results with Kibana.

Our SpyStudio tool intercepts application system calls and retrieves the called functions by inspecting the call-stack.

We were unable to access stack information in the last few 64-bit releases of Microsoft Office products. When we use SpyStudio to intercept an Office installation or most Office applications like Word or Excel, they start normally, but eventually exit silently.

Our initial research showed the culprit to be the Office Software Protection Platform, which would make sense, as it is supposed to hide an application’s safety mechanisms.

However, the Office Software Protection Platform did not keep us from intercepting the 32-bit version of Microsoft Office, so we decided to investigate further.

The .pdata Section

How does the 64-bit operating system do a stack walk when an exception occurs, and how can a debugger know who called a function?

Microsoft added new metadata information which is stored on a special section named “.pdata” in the PE file format specification. When an application is compiled, the compiler stores information related to the prolog of each function. If a function handles exceptions, the compiler also stores data about actions that must happen when the unwind operation is executed.

The operating system and the debugger use a series of RUNTIME_FUNCTION structures to retrieve a variety of information about each function, like how much stack space is reserved for each function usage, which callbacks must be called in an unwind operation, and where assembly registers are stored.

If you want to do your own stack walking, you can start from the current program counter (the RIP register in x64) and look for the RUNTIME_FUNCTION that belongs to it. Then process the UNWIND_INFO items to determine stack usage, and lastly, retrieve the location of the return address of the parent function.

Because the .pdata section is created when the application is compiled, if the program generates dynamic code, like the .NET JIT profiler does, it should also create the corresponding RUNTIME_FUNCTION metadata and inform the operating system of the new dynamic code.

The RtlInstallFunctionTableCallback API adds an entry in an internal processes table maintained by NtDll.dll that helps RtlLookupFunctionEntry and RtlVirtualUnwind find information on how to walk the stack when your dynamically generated code is in the middle of the function calls chain.

Microsoft Office Installer and Applications

So what explains the silent exit of an Office application like Word?

At first we thought that some kind of intentional data corruption was happening in the internal table. It seemed like some kind of anti-debugging technique to keep reverse engineers from seeing the product activation mechanism.

After some trial and error we noticed that RtlInstallFunctionTableCallback was installing a callback to a suspicious routine. Surprisingly, that routine calls TerminateProcess API! When our stack walker function wanted to know the chain of calls, RtlLookupFunctionEntry indirectly called that routine and the program terminated silently.

Could the guys at Microsoft have decided to use this strange method to protect their code? The annoying callback function was added and removed frequently during many operations.

The solution was to add a simple hook to the RtlInstallFunctionTableCallback API to keep it from being added. Now the issue is resolved and the fixed versions of Deviare “Hooking for the Masses” and SpyStudio will be available soon.

Nektra and VMware, Inc. have been collaborating to significantly improve the process of creating and troubleshooting VMware ThinApp application virtualization packages with the SpyStudio application. The video below shows the SpyStudio new ability to harvest applications directly from the operating system to create VMware ThinApp packages even for applications where customers no longer have the installer media. The new SpyStudio release can be downloaded free from http://www.nektra.com/products/spystudio-api-monitor/download/. A fully featured version requires a license.

As companies embrace application virtualization, packaging and troubleshooting in some cases has proven difficult and resource intensive. SpyStudio offers a means to quickly compare application operations to help pinpoint and solve challenging packaging tasks.

The application virtualization market will continue to grow in the next years. Hence, it is critical to be able to make the virtualization process less error prone. Leveraging SpyStudio, a unique and advanced tool will prove to be an essential part of the growth of application virtualization and successful customer implementations.

Hernan has added a new feature to the code offered in our article SQL Server Interception and SQL Injection Attack Prevention. Now it is possible to cancel queries as well as watch them. The code sample uses the Deviare Interception Engine’s call-skipping feature to abort the execution of the CSQLSource::Execute function. The code distribution includes a customized Deviare database for adding the definition of CSQLSource::Execute function parameters. To use this feature you must invoke the application with the “-a” switch in the command line.

We also improved console debugging output and fixed errors that came up when exiting sqlservr.exe. If the developer has a Deviare license, it can be added as a license.txt file in the application directory to disable the splash window.

Zero day vulnerabilities put organizations at the mercy of vendors. These vulnerabilities are like a ticking bomb: you do not know when someone will exploit them. Writing your own patch for closed source applications is, in most cases, a complex mission that can take even longer than the vendor solution. When you use legacy software which has outlived vendor support you must write your own patch or set up preventive measures. Even if you are using supported software, you can use Deviare to protect yourself from some known 0-day vulnerabilities to 0-day attacks until the vendor patch is available. Below is a code sample which uses Deviare to address CVE-2010-3971. Deviare makes hooking extremely easy, requiring only the most rudimentary programming skills. Deviare is binary instrumentation for the masses!

CVE-2010-3971 is a vulnerability in the CSharedStyleSheet::Notify function in the CSS parser in mshtml.dll. It uses memory after it is freed. We use Deviare to intercept the exploit before the attack is made effective and can achieve a denial of service or execution of arbitrary code.

The CSharedStyleSheet::Notify function manipulates an array of CStyleSheet objects. The function receives a flag as a parameter. If this flag passed is one, it calls CStyleSheet::Notify. The exploit must embed the value of the flag to call this particular function.

Our code hooks the CStyleSheet::Notify function, which is not normally called by Internet Explorer, in all iexplorer.exe processes, to detect the presence of an exploit. We use Metasploit to simulate the attack with the ms11_003_ie_css_import exploit and check our detection method. If an exploit is detected, a message box appears and IE is suspended to prevent damage.
Below is a video showing the attack and defense in action:

Code

Prerequisites

Download Deviare and register it for 32-bit or 64-bit

To enable the Deviare engine to use debugging symbols, the following library files are required: symsrv.dll which can be obtained in the Debugging Tools for Windows package and msdiaXX.dll which is part of the DIA SDK, available in Microsoft Visual Studio installation folder, under DIA SDK/bin directory. The Recommended Debugging Tools for Windows version is 6.12.2633 or higher. Tested DIA SDK versions are 9.0 (msdia90.dll), 10.0 (msdia100.dll) and 11.0 (msdia110.dll).

You must copy those 32 and/or 64-bit DLLs to the dllx86 and dllx64 folders in the “bin” directory of the project, depending on which platforms you want to target.

The project platform should match the Internet Explorer platform for the interception to succeed.

Many different proxy servers are used to intercept HTTP traffic. Fiddler is the most popular one for generic purposes. Burp Proxy is the leader for security testing. The issue with intercepting HTTPS traffic is that the proxy application acts as the man in the middle for HTTPS requests and the certificates being presented to the client are not the real ones. For example, intercepting network traffic to Amazon leads to a warning in the browser because the certificate being presented is unsigned. Another issue is that it is time consuming to set up the keys and certificates needed to configure the proxy.

Instead of using a proxy, you can intercept the EncryptMessage function in the Secure32.dll as HookME does:

You can also intercept the WinINet.dll before data is encrypted in the HTTPS request, and after data is decrypted in the HTTPS response. This way, no change is made to any certificate and no man in the middle attack is simulated. These concepts are a starting point for more sophisticated web security, debugging tools, and support for Firefox and Chrome browsers. You can start by intercepting synchronous functions in WinINet.DLL such as InternetOpen, HttpOpenRequest, HttpSendRequest, HttpAddRequestHeaders, InternetReadFile, InternetWriteFile, and their “Ex” functions counterpart.

What is your computer’s maximum render quality, resolution, and frames per second for Battlefield 3? Hard core gamers are eager to show off their expensive, tuned setup at its full potential. Overclocked processors and computers cooled with liquid hydrogen are lovely parts of the gaming folklore. The source code below instruments Direct3D 9 applications to calculate frames per second and capture video. It produces an AVI container using the video codec of your choice. It is also possible to capture game screenshots in the 32-bit BMP format by pressing “delete”. The shortcuts for starting and stopping video recording are “F11” and “F12”.

The code we have provided starts the target process in suspended mode, and hooks the Direct3DCreate9 entry point in the d3d9.dll.

Once we catch a Direct3DCreate9 call, we can use the returned IDirect3D9 pointer to index the VTable. Since the call occurred in the target process address space, we cannot use the pointer directly in our host application; however, we can use Deviare’s functions to read the hooked process memory (starting with the IDirect3D9 pointer) to get the method addresses. This is a very interesting and useful technique which avoids sending address data from the intercepted process to the host processes [1].

We use the object’s VTable address to get the address of the CreateDevice method and hook the device creation with INktSpyMgr::CreateHookForAddress and INktSpyMgr::AddCustomHandler. Note that the resulting events INktSpyMgr will trigger both local hook handlers in the SpyMgr host process, and remote hook handlers in the intercepted process. The local handler creates hooks for IDirect3DDevice9::EndScene, IDirect3DDevice9::Reset, IDirect3DDevice9::Present, and IDirect3DDevice9::Release using the remote VTable indexing technique. The remote handler initializes the FPS display, keyboard hook, font, and sprite resources for the console.

All hooking is done from the Deviare host executable. The plugin that resides in the target process address space does not create additional Deviare hooks. Once all needed IDirect3DDevice9 methods are successfully hooked, we can focus on implementing video capture and FPS display.

In order to implement video capture and FPS display we must define the behavior of the pre-call and post-call handlers for the Present, EndScene, and Reset methods.

In the pre-call to Present, we peek at the first item in the keyboard command queue to check for user actions. If it is the “take screenshot” command, we read the current display device backbuffer and save it to disk. If the first item is the “start recording” command, we create and setup the AVI Video file and it’s streams. If it is the “stop recording” command, we simply close the AVI file if it was recording frames. If video recording has been enabled, we add a frame to the current AVI file and update the frame per second statistics. The number of frames recorded depends on the specified frame rate (the default is 15).

In the pre-call to EndScene, if the device is not currently in a reset state, we update the console and frame counter text in the display. If it was not changed, it is simply redrawn with the current string buffer.

Pre-call handling of device Reset occurs when windows are resized, video mode changes, or fullscreen mode is entered or exited. If video is being recorded we stop recording since we do not handle multiple resolution streams in our code. Next, we release our font and sprite resources, and our backing display surface. During post-call Reset function handling, we also check for video recording. Additionally, we recreate the surface, sprite and font resources that we released in the Reset pre-call stage.

Possible Improvements

This code can be improved to include instrumentation of DirectX 11 as well as OpenGL applications and games. The technique would be similar. DirectX 10/11 applications use DXGI low-level interfaces to swap back and front buffers and there are no “lost devices”, so instead of hooking EndScene, Present, and Reset, we would hook DXGI library function calls. This approach would be easier than instrumenting DirectX9, since display device handling is simplified.

Audio Capture: Windows Vista and later systems direct all DirectX audio streams through the native AudioSession APIs. The easiest way to capture audio is through the documented loopback audio device. The limitation is that all system audio is captured, not only audio from our desired application.

If audio isolation is required, hooking the IAudioRenderClient interface should copy audio buffer data into user application memory. Audio data could then be transferred to the audio stream in the AVI file.

The key problem of audio capturing is resampling. If the sample rate and bit depth of the AVI stream and audio buffer do not match, the audio must be resampled. Writing a good resampler is not trivial task. Our Audio Recorder SDK provides a basic and fast resampling code.

Using Deviare to Cheat on Games

This simple Deviare code allows you to to see through game walls. We intercept Direct3D objects and select wireframe mode so the walls are transparent. This code injects a DLL to create an object based on the IDirect3D9 interface and hook the address of the CreateDevice COM method from the virtual table. The hooked CreateDevice COM method receives an object with IDirect3DDevice9 interface, which is used to set the wireframe mode by calling pDeviceInterface->SetRenderState(D3DRS_FILLMODE, D3DFILL_WIREFRAME). The pDeviceInterface->SetRenderState(D3DRS_FILLMODE, D3DFILL_SOLID) call reverts to the solid mode. You can switch between the wireframe and the solid modes by using the INSERT and DELETE keys.

Deviare can be used to develop a lot of other game tools. Some ideas to try yourself are:

Hooking the random function in the Minesweeper to return zero and solve the game with just one click

It would be a dangerous thing for the gamer community if streamed online games such as OnLive succeeded. You cannot reverse engineer the cloud. Game cheating has a long early history, it would be bad to cut it. Gamers have been cheating on video games since their invention. It would be a shame to stop the fun.

Our Deviare hooking engine can be used to hook into Microsoft SQL Server 2012 RTM (11.00.2100.60) and 2014 CTP1 queries at the application level. Tools like WireShark use a different approach since they intercept SQL Server traffic at the network level. The key benefits of intercepting queries at the application level are:

Since the query is a string you do not need to understand a protocol to retrieve it

As the query is received on a single point, you do not have to handle a variety of communication channels between the client and the server

It is possible to change the flow of the application and modify or cancel a query

In 2013, the most critical security risk is injection. Our code can be used to develop your own monitoring and mitigation tool. With a lot of zero day bugs around it is not possible to depend only on vendors and their hotfixes. The problem is even worse for closed source applications. For example, Microsoft is ending support for Windows XP on April 8, 2014. How can your organization deal with that? The three main options are:

Code

Prerequisites

To enable the Deviare engine to use debugging symbols, the following library files are required: symsrv.dll which can be obtained in the Debugging Tools for Windows package and msdiaXX.dll which is part of the DIA SDK, available in Microsoft Visual Studio installation folder, under DIA SDK/bin directory. The Recommended Debugging Tools for Windows version is 6.12.2633 or higher. Tested DIA SDK versions are 9.0 (msdia90.dll), 10.0 (msdia100.dll) and 11.0 (msdia110.dll).

You must copy those 32 and/or 64-bit DLLs to the dllx86 and dllx64 folders in the root directory of the project, depending on which platforms you want to target.

SQL Server SQLSERVR.EXE service platform should match the project architecture for the interception to succeed.

Use

Compile the solution

Make sure sqlservr.exe service is running

Copy all database files from the project’s DB folder into the binary output folder. See below for information about user-defined databases.

Run SQLSvrIntercept.exe from the commandline with Administrator rights. It will load and cache the symbols under c:\symbols and then displays “Ready.”.

Development Notes

If the application will be deployed to a Microsoft Windows environment which does not have Visual Studio 2012, make sure that the runtime C++ dependencies are available. If they are missing:

To deploy the Debug compilation you can copy the library from %ProgramFiles%\Microsoft Visual Studio 11.0\VC\redist\Debug_NonRedist\x64\Microsoft.VC110.DebugCRT to the System32 directory in the destination computer.

To deploy the Release compilation you can copy the %ProgramFiles%\Microsoft Visual Studio 11.0\VC\redist\x64\Microsoft.VC110.CRT to the System32 directory in the destination computer, or install the Visual Studio 2012 Redistributables from http://www.microsoft.com/en-us/download/details.aspx?id=30679

Generating User Defined Databases

Deviare offers many advanced features such as counting, inspecting and dereferencing function parameters, getting parameter types, and intercepted function skip. A database containing the function signature is required for those features to work with a specific function.

The default Deviare databases are enough for most standard operating system libraries.
However, in case you need to intercept a function that is not present in the default databases, Deviare provides a tool to generate user defined databases. This tool is located in the Deviare-DbGenerator distribution. It should be fed with a C header file containing the function and type definitions to add.

A simple example (along with our own CSQLSource::Execute signature definition) is included in the DB folder for this project. The database files were generated from the sample BASE.H file.

Note that databases are not required for basic interception: you can intercept an anonymous function by specifying its address. However databases are required for query blocking, which uses the Deviare’s call-skipping feature.

Acknowledgments

Nektra’s Hernan Di Pietro wrote the SQL Server interception tool. After researching a bit without finding the correct function to hook he asked on Reverse Engineering Q&A where Brendan Dolan-Gavitt kindly pointed him to the correct function, allowing him to complete the project.

Notes

Some of Microsoft’s product versions do not have public debugging symbols, which are required in order to use the SQL Server interception tool