Code Monkey home page Code Monkey logo

rafzi / hacklib Goto Github PK

View Code? Open in Web Editor NEW
35.0 2.0 9.0 1.67 MB

Hacklib is a C++ library for building applications that run as a shared library in another application. It provides general purpose functionality like pattern scanning, hooking and laying out foreign classes. Additionally it contains some D3D and OpenGL drawing facilities and a cross-platform, high-performance, 3D-capable, transparent overlay.

CMake 0.13% C 37.95% C++ 61.92%
hooking memory-hacking overlay pattern-matching

hacklib's Introduction

Hacklib

Hacklib is a C++ library for building applications that run as a shared library in another application. It provides general purpose functionality like pattern scanning, hooking and laying out foreign classes. Additionally it contains some D3D and OpenGL drawing facilities and a cross-platform, high-performance, 3D-capable, transparent overlay.

Every component in this project can target 32-bit x86 Windows and most of it targets 64-bit x86_64 Windows as well. Some stuff should work on every platform that has a modern C++ compiler.

Example projects

This repository contains a couple simple examples already:

  • injector: A command line application to inject shared libraries into processes. This is the tool to get your projects into target applications.
  • test: An automatic test application.
  • disableGfx: A simple project that may be able to double your FPS in D3D9 games. But at what cost?
  • veh_benchmark: Comparison of VEH hooking implementations.

Bigger examples are located in separate repositories:

  • hacklib_csgo: A minimal example for a real-world target Counter-Strike: Global Offensive. (Cross-platform)
  • hacklib_gw2: Graphical information gathering tool for Guild Wars 2.
  • hacklib_bf: A game hack for the Battlefield series.
  • D3D_ok: A library that makes the DirectX 9 3D API do nothing to save resources.

Features

Main.h

A helper / framework for implementing a shared library that runs by itself after it is loaded into the target process.

#!c++

class MyMain : public hl::Main
{
public:
    bool init() override
    {
        // Your init code here. Return true to loop on step member function afterwards.
        return false;
    }
};

hl::StaticInit<MyMain> g_main;

WindowOverlay.h

A cross-platform high performance 3D-capable transparent overlay. Will follow a target window and always draw on top of it with the ability have transparency on the overlay. Can be rendered to with D3D on Windows and OpenGL on Linux. Requires the compositing window manager introduced with Windows Vista (always active since Windows 8). The X Window System is required on Linux.

For an example see Drawer.h section below.

IDrawer.h / DrawerD3D.h / DrawerOpenGL.h

Wrapper for drawing with D3D or OpenGL in a resource-safe C++ way.

#!c++

hl::DrawerD3D drawer;
hl::WindowOverlay overlay;

if (overlay.create() != hl::WindowOverlay::Error::Okay)
    return false;

overlay.registerResetHandlers([&]{ drawer.onLostDevice(); }, [&]{ drawer.onResetDevice(); });
drawer.setContext(overlay.getContext());

while (true)
{
    overlay.beginDraw();
    drawer.drawCircle(100, 100, 30, hl::Color(150, 255, 100, 50));
    overlay.swapBuffers();
}

Hooker.h

Implements various hooking methods like simple JMP redirection, convenient JMP detours, virtual table hooks and vectored exception handler hooking.

The implemented VEH hooking mechanism is about 3x faster than the conventional PAGE_NOACCESS implementation. See the project veh_benchmark for a comparison.

PatternScanner.h

Provides pattern scanning techniques like masked search strings or search by referenced strings in the code of the target process.

#!c++

uintptr_t MapIdSig = hl::FindPattern("00 ?? 08 00 89 0d");

hl::PatternScanner scanner;
auto results = scanner.find({
    "ViewAdvanceDevice",
    "ViewAdvanceAgentSelect",
    "ViewAdvanceAgentView"
});

void *pAgentSelectionCtx = *(void**)(hl::FollowRelativeAddress(results[1] + 0xa) + 0x1);

Logging.h

Convenient printf-like logging macros. Source information with file name, line number and function name are included in debug builds.

#!c++

// The default configuration also logs to a file next to the library.
hl::LogConfig logCfg;
logCfg.logFunc = [](const std::string& msg){ std::cout << msg << std::flush; };
hl::ConfigLog(logCfg);

HL_LOG_DBG("This is only shown in debug builds. printf formatting: %i\n", 3);
HL_LOG_ERR("This is always shown\n");
HL_LOG_RAW("This will log just the given input without source information or time\n");

Memory.h

Various utilities for memory allocation, protection and mappings.

Patch.h

Object wrapper around a simple code patch. Takes care of memory protection and restores everything on destruction.

#!c++

hl::Patch p1, p2;
p1.apply(0x00111111, (uint8_t)0xeb);
p2.apply(0x00222222, "\x90\x90\x90", 3);

Injector.h

A way to forcibly get your shared library into the target process. For a tool building on this functionality see the ldr project.

ConsoleEx.h

A high performance Windows console that accepts input and output simultaneously.

D3DDeviceFetcher.h

Finds the D3D device used for rendering by the host application in a generic way.

#!c++

auto pDev = hl::D3DDeviceFetcher::GetD3D9Device();

ForeignClass.h

Helper class for accessing a foreign class dynamically at runtime, including doing virtual member function calls.

#!c++

void *ptr = 0x12345678;
hl::ForeignClass obj = ptr;
int result = obj.call<int>(0x18, "Hello World", 3.14f, 42);
double value = obj.get<double>(0x6c);
obj.set(0x70, value+7);

ImplementMember.h

Macros for declaring a foreign class statically in a type-safe, const-safe and simply convenient manner.

#!c++

class CPlayer
{
    // Declare virtual table function by offset
    IMPLVTFUNC(double, someFunc, 0x1c, int, id, double, speed);
    // Declare virtual table function by ordinal
    IMPLVTFUNC_OR(void, boop, 3);
    // Declare member variable by offset
    IMPLMEMBER(int, Id, 0x10);
    // Declare member variable by relative offset
    IMPLMEMBER_REL(D3DXVECTOR3, Pos, 0x8, Id);
    IMPLMEMBER_REL(float, Hp, 0, Pos);
};

CrashHandler.h

A wrapper that catches system exceptions like memory access faults. The handlers should never be called in working programs, because C++ destructors are not called when a fault occurs.

#!c++

hl::CrashHandler([]{
    int crash = *(volatile int*)nullptr;
}, [](uint32_t code){
    printf("Crash prevented. code: %08X\n", code);
});

ExeFile.h

An abstraction for PE or ELF executable images.

Utility

These are not really related to the topic of this library, but might often be used in a program built from this library.

Rng.h:

#!c++

hl::Rng rng;

while (true)
{
    // From 0 to 100
    int a = rng.nextInt(0, 100);
    // From 7.1 to 10.3
    auto b = rng.nextReal(7.1, 10.3);
}

Timer.h:

#!c++

hl::Timer t;
// Some computation.
std::cout << t.diff() << std::endl;
t.reset();
// Another computation.
std::cout << t.diff() << std::endl;

Input.h:

#!c++

hl::Input input;

while (true)
{
    input.update();
    if (input.isDown(VK_SHIFT))
    {
        if (input.wentDown('F'))
        {
            // Shift was held and F changed state from not pressed to pressed.
        }
    }
}

Dependencies

Hacklib is written in modern C++ and requires a recent compiler. The build was tested with Visual Studio 2017, GCC 4.8, GCC 4.9, Clang 3.3 and Clang 3.5 with C++14 support enabled. Use the vs2013 or vs2015 tag for an outdated version that works for Visual Studio 2013 or 2015.

The project is using CMake and requires version 3.1 or later.

Graphics related components require the DirectX SDK June 2010 on Windows or on Linux the X11 and OpenGL libraries. The essential headers and libraries of the DirectX SDK are included in this repository. Required Linux packages would for example be on Debian/Ubuntu: sudo apt-get install libx11-dev mesa-common-dev libglu1-mesa-dev libxrender-dev libxfixes-dev libglew-dev.

How to build

  • Run CMake
  • Build the project that was generated by CMake
  • For your own project folders, it is most convenient to put them into the hacklib/src folder. Then provide a CMakeLists file in this folder. For example: hacklib/src/YourProject/CMakeLists.txt. You need to re-run CMake manually after adding your project folder, it will not detect the new folder itself. The basic CMakeLists file is the following, add source files as neccessary to the ADD_LIBRARY command:
#!cmake

PROJECT(YourProject)

ADD_LIBRARY(${PROJECT_NAME} SHARED main.cpp)

SET_TARGET_PROPERTIES(${PROJECT_NAME} PROPERTIES FOLDER ${PROJECT_NAME})

TARGET_LINK_LIBRARIES(${PROJECT_NAME} hacklib)

Contribute

Please use the issue tracker and submit pull requests to contribute.

License

Free to use for any purpose. Don't claim you wrote the code or modified versions. If you release code or binaries give credit and link to this repository.

If you are making money with this code, please consider sharing a bit!

Paypal Donate Link

hacklib's People

Contributors

charlyzard avatar fatalis avatar hairys avatar rafzi avatar sehoffmann avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar

hacklib's Issues

Help with window overlay

Hello, I have an opengl game that i want to put an overlay on, I'm trying the following but it doesn't seem to do something when I load the module (it seems to get loaded correctly). Am i doing something wrong ?

#include "hacklib/Main.h"
#include "hacklib/ConsoleEx.h"
#include "hacklib/D3DDeviceFetcher.h"
#include "hacklib/Hooker.h"
#include <cstdio>


#include "hacklib/DrawerD3D.h"
#include "hacklib/DrawerOpenGL.h"
#include "hacklib/WindowOverlay.h"


hl::StaticInit<class MyMain> g_main;
const hl::IHook *g_indexedHook;


class MyMain : public hl::Main
{
private:
    hl::WindowOverlay overlay;
#ifdef _WIN32
    hl::DrawerD3D drawer;
#else
    hl::DrawerOpenGL drawer;
#endif
public:
    bool init() override
    {
        if (overlay.create() != hl::WindowOverlay::Error::Okay)
        {
            hl::MsgBox("Error", "Could not create overlay");
            return false;
        }

        overlay.registerResetHandlers([&] { drawer.onLostDevice(); }, [&] { drawer.onResetDevice(); });
        overlay.setTargetRefreshRate(100);
        drawer.setContext(overlay.getContext());


        return true;
    }

    bool step() override
    {
        if (GetAsyncKeyState(VK_HOME) < 0)
            return false;

        overlay.beginDraw();
        drawer.drawCircle(100, 100, 50, hl::Color(100, 255, 100, 50));
        overlay.swapBuffers();

        return true;
    }

    hl::Hooker m_hooker;
    hl::ConsoleEx m_con;
};

Hello, please help. This library failed to compile with hacklib_gw2.

Hello, I'm compiling the hacklib_gw2 library, and following the instructions, I put it under the hacklib/src folder.
when I opened the vs2017 project file hacklib_project.sln after cmake, I got an error when compiling:

C2039 'RSI': not a member of 'hl::CpuContext_x86' hacklib_gw2 (hacklib_gw2\hacklib_gw2)
C2039 'RDI': not a member of 'hl::CpuContext_x86' hacklib_gw2 (hacklib_gw2\hacklib_gw2)

I found that the problem came from the definition of CpuContext under hooker.h:

#ifdef ARCH_64BIT
typedef CpuContext_x86_64 CpuContext;
#else
typedef CpuContext_x86 CpuContext;
#endif

And CMakeLists.txt has defined the following conditions:

IF(CMAKE_SIZEOF_VOID_P EQUAL 8)
    SET(ARCH_64BIT TRUE)
    ADD_DEFINITIONS(-DARCH_64BIT)
    SET(PROJ_BIN        ${PROJ_ROOT}/bin64)
    SET(PROJ_LIB        ${PROJ_ROOT}/lib64)
ELSE()
    SET(PROJ_BIN        ${PROJ_ROOT}/bin)
    SET(PROJ_LIB        ${PROJ_ROOT}/lib)
ENDIF()

I don't know why he didn't define it as CpuContext_x86_64, which caused the compilation to fail.
I hope you can take the time out of your busy schedule to answer my questions, I'd be very grateful!

Please help me understand hookDetour

I havent worked with hooks for a while, I remember doing it with microsoft detours library.
It was super simple because you just called it like hook(theirfunc, myfunc);

I am having trouble understanding what is nextInstructionOffset. Where am I supposed to be finding this information from? Inside IDA inside the actual function or at the place where the function is called?

I dont want to accidently overwrite any code and what if the function changes later? then I would have to keep rechecking these bytes in IDA every time?

I looked at the usage of this lib in GW2 as reference, I am having trouble understanding why hook(hl::CpuContext *ctx) is better than a standard hook like detours lib?

Also this:
void __fastcall hkGameThread(uintptr_t pInst, int, int frame_time)
{
    auto pCore = g_initObj.getMain();
    static auto orgFunc = ((void(__thiscall*)(uintptr_t, int))pCore->m_hkAlertCtx->getLocation());

    orgFunc(pInst, frame_time);
}

Why is the params have an extra int and the orgfunc does not? I remember doing something similar for a different calling declaration but not sure if it was __fastcall or __thiscall, sorry been so long since I messed around with it.

Would really appreciate an explanation, love the lib btw, the pattern scanning stuff is super good. It would be cool to be able to search for a function that has two string refs within it, because sometimes the function list in ida returns too many references and it would be cool to narrow it down to a single function easily.

DirectDraw Exclusive Mode compatibility and potential Feature Request to be used from other process

Hi! Very nice and interesting project. Thank you for sharing!

I'm developing a cross-plaform System Monitor (on Python3, just for fun and personal use... or whoever else wants to use it!) which graphically shows key system values (CPU usage and temp, Disk usage, Memory usage, GPU usage, temp and fan speed). It also shows an FPS counter to check in-game performance. The problem is that it doesn't stays on top when working with games using DirectDraw Exclusive Mode, making it useless. After searching a lot I have realized that it can only be done by hooking D3D dll, but this can not be done with Python. Your WindowOverlay is very promissing, so I have two questions:

  • Does it work with DirectDraw Exclusive Mode applications (reading the docs, I assume it does)?
  • Is it possible to somehow address the overlay from a separate process so you can draw some info on it (just text could be enough) and, if so, how?

The main problem is that I am totally unskilled in C, my apologies for that. Perhaps we could work on a Python wrapper for the whole thing if you think it's interesting. I believe I can do or help you to do that (as a first idea, loading the C code built as DLL's and exposing its API in a python module).

Thank you in advance for your time and patience!

Captura de pantalla 2023-01-11 122150
Captura de pantalla 2023-01-11 122256
Captura de pantalla 2023-01-11 122225

execFunc() failed

Testing logging functionality.
Test log: [Expected: "Test message"]
Test message
Starting test: "TestMemory"
Assertion 'execFunc()' failed.
msg: Could execute read-only page
in C:\Users\╩╥\Desktop\hacklib-master\src\test\test.cpp:303
func: TestMemory

What's happened?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.