Repository: hasherezade/IAT_patcher Branch: master Commit: e059f3388fa4 Files: 62 Total size: 155.0 KB Directory structure: gitextract_0hk22p70/ ├── .appveyor.yml ├── .gitignore ├── .gitmodules ├── .travis.yml ├── CMakeLists.txt ├── LICENSE ├── README.md ├── build.sh ├── iatp_autobuild.sh ├── patcher/ │ ├── .gitignore │ ├── CMakeLists.txt │ ├── ExeController.cpp │ ├── ExeController.h │ ├── ExeHandler.cpp │ ├── ExeHandler.h │ ├── ExeHandlerLoader.cpp │ ├── ExeHandlerLoader.h │ ├── Executables.cpp │ ├── Executables.h │ ├── FileLoader.cpp │ ├── FileLoader.h │ ├── FuncReplacements.cpp │ ├── FuncReplacements.h │ ├── IAT_Patcher.rc │ ├── ImportsLookup.cpp │ ├── ImportsLookup.h │ ├── ImportsTableModel.cpp │ ├── ImportsTableModel.h │ ├── InfoTableModel.cpp │ ├── InfoTableModel.h │ ├── LICENSE │ ├── README.md │ ├── ReplacementsDialog.cpp │ ├── ReplacementsDialog.h │ ├── StubMaker.cpp │ ├── StubMaker.h │ ├── application.qrc │ ├── dllparse/ │ │ ├── FunctionsModel.cpp │ │ ├── FunctionsModel.h │ │ ├── LibraryInfo.cpp │ │ ├── LibraryInfo.h │ │ ├── LibraryParser.cpp │ │ ├── LibraryParser.h │ │ ├── LibsModel.cpp │ │ └── LibsModel.h │ ├── main.cpp │ ├── mainwindow.cpp │ ├── mainwindow.h │ ├── mainwindow.ui │ ├── replacements.ui │ ├── resource.h │ └── stub/ │ ├── Stub.cpp │ ├── Stub.h │ ├── Stub32.cpp │ ├── Stub32.h │ ├── Stub32Data.h │ ├── Stub64.cpp │ ├── Stub64.h │ └── Stub64Data.h └── stub/ ├── hexf.cpp ├── stub32.asm └── stub64.asm ================================================ FILE CONTENTS ================================================ ================================================ FILE: .appveyor.yml ================================================ os: - Visual Studio 2015 platform: x64 - x64 branches: only: - master install: - git submodule update --init --recursive - set PATH=C:\Program Files\CMake\bin;%PATH% build: verbosity: detailed configuration: - Release environment: artifactName: $(APPVEYOR_PROJECT_NAME)-$(APPVEYOR_REPO_COMMIT)-$(CONFIGURATION) matrix: - env_arch: "x64" QT5: C:\Qt\5.11\msvc2015_64 - env_arch: "x86" QT5: C:\Qt\5.11\msvc2015 before_build: - set PATH=%PATH%;%QT5%\bin;%QT5%\lib\cmake - set Qt5Core_DIR=%QT5% - mkdir build - cd build - if [%env_arch%]==[x64] ( cmake .. -A x64 ) - if [%env_arch%]==[x86] ( cmake .. ) build_script: - cmake --build . --config %CONFIGURATION% after_build: - mkdir %artifactName% - cp -r patcher/%CONFIGURATION%/* %artifactName% - cp %QT5%\bin\Qt5Core.dll %artifactName% - cp %QT5%\bin\Qt5Gui.dll %artifactName% - cp %QT5%\bin\Qt5Widgets.dll %artifactName% - mkdir %artifactName%\platforms - mkdir %artifactName%\styles - mkdir %artifactName%\imageformats - cp %QT5%\plugins\platforms\qwindows.dll %artifactName%\platforms - cp %QT5%\plugins\styles\qwindowsvistastyle.dll %artifactName%\styles - cp %QT5%\plugins\imageformats\qico.dll %artifactName%\imageformats artifacts: - path: build\%artifactName% ================================================ FILE: .gitignore ================================================ build/ ================================================ FILE: .gitmodules ================================================ [submodule "bearparser"] path = bearparser url = https://github.com/hasherezade/bearparser.git ================================================ FILE: .travis.yml ================================================ language: cpp sudo: true os: - linux compiler: - gcc - clang addons: apt: packages: - qt5-default - qt5-qmake before_script: - cmake --version - qmake -v script: - mkdir build - cd build - mkdir $(pwd)/out - cmake -DCMAKE_INSTALL_PREFIX:PATH=$(pwd)/out .. - cmake --build . --target install ================================================ FILE: CMakeLists.txt ================================================ cmake_minimum_required (VERSION 2.8) project (IAT_Patcher) # modules: set ( M_BEARPARSER "bearparser/parser" ) set ( M_IATP "patcher" ) # modules paths: set (PARSER_DIR "${CMAKE_SOURCE_DIR}/${M_BEARPARSER}" CACHE PATH "BearParser main path") set (PARSER_INC "${PARSER_DIR}/include" CACHE PATH "BearParser include path") set (IATP_DIR "${CMAKE_SOURCE_DIR}/${M_IATP}" CACHE PATH "IATPatcher main path") # Add sub-directories # # libs add_subdirectory (${M_BEARPARSER}) set (PARSER_LIB bearparser CACHE FILE "BearParser library path") # executables add_subdirectory(patcher) # dependencies add_dependencies(IAT_Patcher bearparser) ================================================ FILE: LICENSE ================================================ Copyright (c) 2014-2016, hasherezade All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ================================================ FILE: README.md ================================================ IAT patcher ========== [![Build status](https://ci.appveyor.com/api/projects/status/dv42sbge09b3i77h?svg=true)](https://ci.appveyor.com/project/hasherezade/iat-patcher) [![Build status](https://travis-ci.org/hasherezade/IAT_patcher.svg?branch=master)](https://travis-ci.org/hasherezade/IAT_patcher) [![Codacy Badge](https://api.codacy.com/project/badge/Grade/e5a1d1892c2642faba08d678c0a6fbf6)](https://www.codacy.com/manual/hasherezade/IAT_patcher?utm_source=github.com&utm_medium=referral&utm_content=hasherezade/IAT_patcher&utm_campaign=Badge_Grade) [![Total alerts](https://img.shields.io/lgtm/alerts/g/hasherezade/IAT_patcher.svg?logo=lgtm&logoWidth=18)](https://lgtm.com/projects/g/hasherezade/IAT_patcher/alerts/) [![GitHub release](https://img.shields.io/github/release/hasherezade/IAT_patcher.svg)](https://github.com/hasherezade/IAT_patcher/releases) [![Github All Releases](https://img.shields.io/github/downloads/hasherezade/IAT_patcher/total.svg)](https://github.com/hasherezade/IAT_patcher/releases) **Persistent IAT hooking application (for PE files).** 📖 Read more: http://hasherezade.github.io/IAT_patcher/ Please report any bugs and remarks to: [issues](https://github.com/hasherezade/IAT_patcher/issues). Requires: + bearparser: https://github.com/hasherezade/bearparser + Qt5 SDK + Qt5 Core + Qt5 GUI + cmake http://www.cmake.org ## Clone Use recursive clone to get the repo together with the submodule: ``` git clone --recursive https://github.com/hasherezade/IAT_patcher.git ``` ## Autobuild To build it on Linux or MacOS you can use the given script - it automatically downloads this repository and all the dependencies:
[iatp_autobuild.sh](https://raw.githubusercontent.com/hasherezade/IAT_patcher/master/iatp_autobuild.sh)
Just run it, and it will automatically download and build everything. ## Download builds You can download the latest stable Windows builds from the [releases](https://github.com/hasherezade/IAT_patcher/releases) ## Sample DLLs Sample DLLs to be used with IAT Patcher can be found in [IAT_patcher_samples](https://github.com/hasherezade/IAT_patcher_samples) ================================================ FILE: build.sh ================================================ #!/bin/bash echo "Trying to autobuild IAT_patcher..." #QT check QT_VER=`qmake -v` str=$QT_VER substr="Qt version 5" echo $QT_VER if [[ $str == *"$substr"* ]]; then echo "[+] Qt5 found!" else str2=`whereis qt5` substr2="/qt5" if [[ $str2 == *"$substr2"* ]]; then echo "[+] Qt5 found!" else echo "Install Qt5 SDK first" exit -1 fi fi CMAKE_VER=`cmake --version` CMAKEV="cmake version" if echo "$CMAKE_VER" | grep -q "$CMAKEV"; then echo "[+] CMake found!" else echo "[-] CMake NOT found!" echo "Install cmake first" exit -1 fi mkdir build echo "[+] build directory created" cd build mkdir $(pwd)/out cmake -DCMAKE_INSTALL_PREFIX:PATH=$(pwd)/out .. cmake --build . --target install ================================================ FILE: iatp_autobuild.sh ================================================ #!/bin/bash echo "Trying to autobuild IAT_patcher..." git clone --recursive https://github.com/hasherezade/IAT_patcher.git echo "[+] IAT_patcher cloned" echo $$ cd IAT_patcher sh build.sh ================================================ FILE: patcher/.gitignore ================================================ ================================================ FILE: patcher/CMakeLists.txt ================================================ cmake_minimum_required(VERSION 3.12) project (IAT_Patcher) message (STATUS "parser_dir='${PARSER_DIR}'") message (STATUS "parser_lib='${PARSER_LIB}'") # Find the QtWidgets library find_package(Qt5Widgets) find_package(Qt5Core) include_directories ( ${PARSER_INC} ) set (stub_hdrs stub/Stub.h stub/Stub32.h stub/Stub64.h stub/Stub32Data.h stub/Stub64Data.h ) set (dllparse_hdrs dllparse/LibraryParser.h dllparse/LibraryInfo.h dllparse/LibsModel.h dllparse/FunctionsModel.h ) set (dllparse_srcs dllparse/LibraryParser.cpp dllparse/LibraryInfo.cpp dllparse/LibsModel.cpp dllparse/FunctionsModel.cpp ) set (hdrs StubMaker.h FuncReplacements.h ImportsLookup.h ExeHandler.h Executables.h ExeController.h InfoTableModel.h ImportsTableModel.h FileLoader.h ExeHandlerLoader.h ReplacementsDialog.h mainwindow.h resource.h ) set (stub_srcs stub/Stub.cpp stub/Stub32.cpp stub/Stub64.cpp ) set (srcs StubMaker.cpp FuncReplacements.cpp ImportsLookup.cpp ExeHandler.cpp Executables.cpp ExeController.cpp InfoTableModel.cpp ImportsTableModel.cpp FileLoader.cpp ExeHandlerLoader.cpp ReplacementsDialog.cpp mainwindow.cpp main.cpp ) set (forms mainwindow.ui replacements.ui ) set (rcc application.qrc ) qt5_add_resources(rcc_src ${rcc}) QT5_WRAP_UI (forms_hdrs ${forms}) QT5_WRAP_CPP (hdrs_moc ${hdrs} ${dllparse_hdrs}) SOURCE_GROUP("Source Files\\Auto Generated" FILES ${hdrs_moc} ${rcc_src} ) SOURCE_GROUP("Source Files\\stub" FILES ${stub_srcs} ) SOURCE_GROUP("Header Files\\stub" FILES ${stub_hdrs} ) SOURCE_GROUP("Source Files\\dllparse" FILES ${dllparse_srcs} ) SOURCE_GROUP("Header Files\\dllparse" FILES ${dllparse_hdrs} ) IF (WIN32) set(CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS} /SUBSYSTEM:WINDOWS /ENTRY:mainCRTStartup") ENDIF() add_executable (IAT_Patcher IAT_Patcher.rc ${hdrs_moc} ${forms_hdrs} ${stub_srcs} ${stub_hdrs} ${dllparse_hdrs} ${dllparse_srcs} ${hdrs} ${srcs} ${rcc_src}) INCLUDE_DIRECTORIES(${CMAKE_CURRENT_BINARY_DIR}) target_link_libraries(IAT_Patcher bearparser Qt5::Core Qt5::Widgets) # dependencies add_dependencies(IAT_Patcher bearparser) #install INSTALL( TARGETS ${PROJECT_NAME} DESTINATION ${CMAKE_INSTALL_PREFIX} COMPONENT ${PROJECT_NAME} ) ================================================ FILE: patcher/ExeController.cpp ================================================ #include "ExeController.h" #include #include bool ExeController::saveExecutable(ExeHandler* exeHndl, QString newFilename) { if (exeHndl == NULL) { return false; } Executable *exe = exeHndl->getExe(); if (exe == NULL) return false; if (AbstractFileBuffer::dump(newFilename, *exe, true) > 0) { exeHndl->onFileSaved(newFilename); emit exeUpdated(exeHndl); return true; } return false; } bool ExeController::hookExecutable(ExeHandler* exeHndl, StubSettings &settings) { bool isSuccess = StubMaker::makeStub(exeHndl, settings); //update view even if hooking partialy failed... StubMaker::fillHookedInfo(exeHndl); emit exeUpdated(exeHndl); return isSuccess; } size_t ExeController::saveReplacementsToFile(ExeHandler* exeHndl, QString fileName) { if (fileName.length() == 0) { return 0; } size_t counter = exeHndl->m_Repl.save(fileName); return counter; } size_t ExeController::loadReplacementsFromFile(ExeHandler* exeHndl, QString fileName) { if (fileName.length() == 0) return 0; size_t counter = exeHndl->m_Repl.load(fileName); if (counter == 0) { return 0; } size_t invalidThunks = exeHndl->m_Repl.dropInvalidThunks(exeHndl->m_FuncMap); counter -= invalidThunks; if (counter != 0) { exeHndl->setUnappliedState(true); } return counter; } ================================================ FILE: patcher/ExeController.h ================================================ #pragma once #include #include "Executables.h" #include "StubMaker.h" class ExeController : public QObject { Q_OBJECT public: enum EXE_ACTION { ACTION_HOOK = 0, ACTION_SAVE, ACTION_UNLOAD, ACTION_RELOAD, ACTION_EXPORT_REPL, ACTION_IMPORT_REPL, COUNT_ACTION }; ExeController(QObject* parent = NULL) {} virtual ~ExeController() { } bool saveExecutable(ExeHandler* exeHndl, QString newFilename); //throws CustomException bool hookExecutable(ExeHandler* exeHndl, StubSettings &settings); //throws CustomException size_t loadReplacementsFromFile(ExeHandler* exeHndl, QString filename); size_t saveReplacementsToFile(ExeHandler* exeHndl, QString filename); signals: void exeUpdated(ExeHandler* exeHndl); }; ================================================ FILE: patcher/ExeHandler.cpp ================================================ #include "ExeHandler.h" bool ExeHandler::defineReplacement(offset_t thunk, FuncDesc newFunc) { bool ret = m_Repl.defineReplacement(thunk, newFunc); if (ret) hasUnapplied = true; emit stateChanged(); return ret; } ================================================ FILE: patcher/ExeHandler.h ================================================ #pragma once #include #include #include "ImportsLookup.h" #include "FuncReplacements.h" class ExeHandler : public QObject { Q_OBJECT signals: void stateChanged(); public: ExeHandler(AbstractByteBuffer *buf, Executable* exe) : m_Buf(buf), m_Exe(exe), isModified(false), hasUnapplied(false), dataStoreRva(INVALID_ADDR) { m_FuncMap.wrap(getImports()); originalEP = exe->getEntryPoint(); m_fileName = (m_Exe) ? m_Exe->getFileName(): ""; connect(&m_Repl, SIGNAL(stateChanged()), this, SLOT(onChildStateChanged())); } virtual ~ExeHandler() { delete m_Exe, delete m_Buf;} Executable* getExe() { return m_Exe; } QString getFileName() { return m_fileName; } bool defineReplacement(offset_t thunk, FuncDesc newFunc); FuncDesc getReplAt(offset_t thunk) { return m_Repl.getAt(thunk); } bool hasReplacements() { return m_Repl.size() > 0; } ImportDirWrapper* getImports() { MappedExe *mappedExe = dynamic_cast(m_Exe); if (mappedExe == NULL) return NULL; return dynamic_cast(mappedExe->getWrapper(PEFile::WR_DIR_ENTRY + pe::DIR_IMPORT)); } void rewrapFuncMap() { this->m_FuncMap.wrap(getImports()); } void setHookedState(bool flag) { isHooked = flag; } bool getHookedState() { return isHooked; } bool getModifiedState() { return isModified; } bool getUnappliedState() { return hasUnapplied; } offset_t getOriginalEP() { return originalEP; } offset_t getCurrentEP() { return m_Exe->getEntryPoint(); } ImportsLookup m_FuncMap; FuncReplacements m_Repl; public slots: void onFileSaved(QString newName) { this->m_fileName = newName; this->isModified = false; //modifications are saved emit stateChanged(); } protected slots: void onChildStateChanged() { emit stateChanged(); } protected: void setUnappliedState(bool flag) { hasUnapplied = flag; } AbstractByteBuffer *m_Buf; Executable* m_Exe; QString m_fileName; bool isModified, hasUnapplied; //TODO: finish and refactor it bool isHooked; offset_t originalEP, dataStoreRva; // TODO: keep params in separate structure friend class StubMaker; friend class ExeController; }; ================================================ FILE: patcher/ExeHandlerLoader.cpp ================================================ #include "ExeHandlerLoader.h" bool ExeHandlerLoader::parse(QString &fileName) { bool isLoaded = false; ExeHandler *exeHndl = NULL; try { const bufsize_t MINBUF = 0x200; AbstractByteBuffer *buf = new FileBuffer(fileName, MINBUF, false); if (buf == NULL) { return false; } ExeFactory::exe_type exeType = ExeFactory::findMatching(buf); if (exeType == ExeFactory::NONE) { delete buf; return false; } Executable *exe = ExeFactory::build(buf, exeType); exeHndl = new ExeHandler(buf, exe); if (exeHndl) { isLoaded = true; } } catch (CustomException &e) { } emit loaded(exeHndl); return isLoaded; } //---- ================================================ FILE: patcher/ExeHandlerLoader.h ================================================ #pragma once #include #include #include #include #include "FileLoader.h" #include "ExeHandler.h" class ExeHandlerLoader : public FileLoader { Q_OBJECT signals: void loaded(ExeHandler *exeHndl); public: ExeHandlerLoader(QString fileName) : FileLoader(fileName) {} virtual bool parse(QString &fileName); }; ================================================ FILE: patcher/Executables.cpp ================================================ #include "Executables.h" #include "StubMaker.h" size_t Executables::size() { QMutexLocker lock(&m_listMutex); //LOCKER return m_Exes.size(); } ExeHandler* Executables::at(size_t index) { QMutexLocker lock(&m_listMutex); //LOCKER if (index >= m_Exes.size()) return NULL; return m_Exes.at(index); } bool Executables::_addExe(ExeHandler *exeHndl) { if (exeHndl == NULL) return false; { //start locked scope QMutexLocker lock(&m_listMutex); //LOCKER m_Exes.push_back(exeHndl); } //end locked scope StubMaker::fillHookedInfo(exeHndl); connect(exeHndl, SIGNAL(stateChanged()), this, SLOT(onChildStateChanged())); return true; } bool Executables::_removeExe(ExeHandler *exe) { QMutexLocker lock(&m_listMutex); //LOCKER size_t indx = m_Exes.indexOf(exe); if (indx != -1) { m_Exes.removeAt(indx); return true; } return false; } QStringList Executables::listFiles() { QStringList fileNames; QList::iterator itr; QString fileName = ""; QMutexLocker lock(&m_listMutex); //LOCKER for (itr = m_Exes.begin(); itr != m_Exes.end(); itr++) { ExeHandler *exeHndl = (*itr); if (exeHndl->getExe() != NULL) { fileName = exeHndl->getFileName(); fileNames << fileName; } } return fileNames; } void Executables::_clear() { QMutexLocker lock(&m_listMutex); //LOCKER QList::iterator itr; for (itr = m_Exes.begin(); itr != m_Exes.end(); itr++) { ExeHandler *exe = (*itr); delete exe; } m_Exes.clear(); } ================================================ FILE: patcher/Executables.h ================================================ #pragma once #include #include #include "ExeHandler.h" class Executables : public QObject { Q_OBJECT signals: void exeListChanged(); public slots: void addExe(ExeHandler *exe) { if (_addExe(exe)) emit exeListChanged(); } void removeExe(ExeHandler *exe) { if (_removeExe(exe)) emit exeListChanged(); } void clear() { _clear(); emit exeListChanged(); } public: size_t size(); ExeHandler* at(size_t index); QStringList listFiles(); protected slots: void onChildStateChanged() { emit exeListChanged(); } private: bool _addExe(ExeHandler *exe); bool _removeExe(ExeHandler *exe); void _clear(); QList m_Exes; QMutex m_listMutex; }; ================================================ FILE: patcher/FileLoader.cpp ================================================ #include "FileLoader.h" #include void FileLoader::run() { QMutexLocker lock(&m_arrMutex); bool parsed = false; try { if (m_FileName == NULL) return; parsed = parse(m_FileName); } catch (...) { } if (!parsed) { emit loadingFailed(m_FileName); } emit loaded(m_Buffer); } bool FileLoader::parse(QString &fileName) { bufsize_t maxMapSize = FILE_MAXSIZE; bool isLoaded = false; try { const bufsize_t MINBUF = 0x200; m_Buffer = new FileBuffer(fileName, MINBUF, false); isLoaded = true; } catch (CustomException &e) { } return isLoaded; } ================================================ FILE: patcher/FileLoader.h ================================================ #pragma once #include #include #include #include class FileLoader : public QThread { Q_OBJECT public: FileLoader(QString fileName) : m_Buffer(NULL), m_Status(false) { m_FileName = fileName; } virtual ~FileLoader() { } signals: void loaded(AbstractByteBuffer *buffer); void loadingFailed(QString fileName); protected: void run(); virtual bool parse(QString &fileName); QString m_FileName; bool m_Status; private: AbstractByteBuffer *m_Buffer; QMutex m_arrMutex; }; ================================================ FILE: patcher/FuncReplacements.cpp ================================================ #include "FuncReplacements.h" bool FuncReplacements::defineReplacement(offset_t thunk, FuncDesc newFunc) { if (_defineReplacement(thunk, newFunc)) { emit stateChanged(); return true; } return false; } bool FuncReplacements::undefReplacement(offset_t thunk) { if (_undefReplacement(thunk)) { emit stateChanged(); return true; } return false; } bool FuncReplacements::_undefReplacement(offset_t thunk) { QMap::Iterator found = m_replacements.find(thunk); bool exist = found != m_replacements.end(); if (exist) { m_replacements.erase(found); return true; } return false; } bool FuncReplacements::_defineReplacement(offset_t thunk, FuncDesc newFunc) { QMap::Iterator found = m_replacements.find(thunk); if (newFunc.size() == 0) { return _undefReplacement(thunk); } if (FuncUtil::validateFuncDesc(newFunc) == false) { return false; } m_replacements[thunk] = newFunc; return true; } FuncDesc FuncReplacements::getAt(offset_t thunk) { if (hasAt(thunk) == false) return ""; return m_replacements[thunk]; } bool FuncReplacements::hasAt(offset_t thunk) { return m_replacements.find(thunk) != m_replacements.end(); } size_t FuncReplacements::load(QString &fileName) { size_t loaded = 0; QFile inputFile(fileName); if ( !inputFile.open(QIODevice::ReadOnly) ) { printf("Cannot open file!"); return 0; } offset_t thunk = 0; QString thunkStr = ""; QString funcDesc = ""; QTextStream in(&inputFile); while ( !in.atEnd() ) { QString line = in.readLine(); QTextStream(&line) >> thunkStr >> funcDesc; bool isOk = false; thunk = thunkStr.toLongLong(&isOk, 16); if (!isOk || !FuncUtil::validateFuncDesc(funcDesc) ) { continue; } if (_defineReplacement(thunk, funcDesc)) loaded++; } inputFile.close(); if (loaded > 0) { emit stateChanged(); } return loaded; } size_t FuncReplacements::save(QString &fileName) { QFile outputFile(fileName); if ( !outputFile.open(QIODevice::WriteOnly | QIODevice::Text) ) return 0; QTextStream out(&outputFile); QMap::iterator itr; size_t counter = 0; for (itr = m_replacements.begin(); itr != m_replacements.end(); itr++) { out << hex << itr.key(); out << " "; out << itr.value(); out << '\n'; counter++; } outputFile.close(); return counter; } size_t FuncReplacements::dropInvalidThunks(ImportsLookup &lookup) { size_t invalidThunks = 0; QList::iterator itr; QList thunks = getThunks(); for (itr = thunks.begin(); itr != thunks.end(); itr++) { if (lookup.hasThunk(*itr) == false) { invalidThunks++; this->_undefReplacement(*itr); } } if (invalidThunks > 0) { emit stateChanged(); } return invalidThunks; } ================================================ FILE: patcher/FuncReplacements.h ================================================ #pragma once #include #include #include "ImportsLookup.h" typedef QString FuncDesc; class FuncUtil { public: static bool validateFuncDesc(FuncDesc library) { int indx = library.lastIndexOf('.'); if (indx == -1) { return false; } QString libName = library.left(indx); QString funcName = library.mid(indx + 1); if (libName.length() == 0 || funcName == 0) return false; return true; } static bool parseFuncDesc(FuncDesc library, QString &libName, QString &funcName) { int indx = library.lastIndexOf('.'); if (indx == -1) { //printf("Invalid library format!\n"); return false; } libName = library.left(indx); funcName = library.mid(indx + 1); if (libName.length() == 0 || funcName == 0) return false; return true; } }; class FuncReplacements : public QObject { Q_OBJECT signals: void stateChanged(); public: FuncReplacements() { } ~FuncReplacements() { } size_t load(QString &fileName); size_t save(QString &fileName); size_t dropInvalidThunks(ImportsLookup &lookup); bool defineReplacement(offset_t thunk, FuncDesc newFunc); bool undefReplacement(offset_t thunk); size_t size() { return m_replacements.size(); } QList getThunks() { return m_replacements.keys(); } FuncDesc getAt(offset_t thunk); bool hasAt(offset_t thunk); protected: bool _undefReplacement(offset_t thunk); bool _defineReplacement(offset_t thunk, FuncDesc newFunc); QMap m_replacements; }; ================================================ FILE: patcher/ImportsLookup.cpp ================================================ #include "ImportsLookup.h" void ImportsLookup::wrap(ImportDirWrapper* imports) { m_Thunks.clear(); m_Imports = imports; if (m_Imports != NULL) { m_Thunks = m_Imports->getThunksList(); } wrapFunctions(); } bool ImportsLookup::hasLib(QString libName) { libName = libName.toUpper(); QMap::iterator itr = m_libs.find(libName); if (itr == m_libs.end()) return false; return true; } bool ImportsLookup::hasFunc(QString funcName) { funcName = funcName.toUpper(); FuncToThunk::iterator itr = m_func.find(funcName); if (itr == m_func.end()) return false; return true; } offset_t ImportsLookup::findThunk(QString libName, QString funcName) { libName = libName.toUpper(); funcName = funcName.toUpper(); QMap::iterator itr = m_libs.find(libName); if (itr == m_libs.end()) return INVALID_ADDR; FuncToThunk &func = m_libs[libName]; FuncToThunk::iterator itr2 = func.find(funcName); if (itr2 == func.end()) return INVALID_ADDR; return m_func[funcName]; } /* protected */ void ImportsLookup::wrapFunctions() { for (size_t i = 0; i < m_Thunks.size(); i++) { offset_t thunk = m_Thunks[i]; if (thunk == 0 || thunk == INVALID_ADDR) continue; QString lib = thunkToLibName(thunk); QString func = thunkToFuncName(thunk); addFunc(lib, func, thunk); } } bool ImportsLookup::addFunc(QString libName, QString funcName, offset_t thunk) { if (libName.size() == 0 || funcName.size() == 0 || thunk == INVALID_ADDR) return false; funcName = funcName.toUpper(); libName = libName.toUpper(); m_libs[libName].insert(funcName, thunk); m_func.insert(funcName, thunk); return true; } ================================================ FILE: patcher/ImportsLookup.h ================================================ #pragma once #include #include #include typedef QMap FuncToThunk; class ImportsLookup : public QObject { Q_OBJECT public: ImportsLookup() { } void wrap(ImportDirWrapper* imports); QString thunkToLibName(offset_t thunk) { return (m_Imports) ? m_Imports->thunkToLibName(thunk) : ""; } QString thunkToFuncName(offset_t thunk) { return (m_Imports) ? m_Imports->thunkToFuncName(thunk) : ""; } bool hasThunk(const offset_t &thunk) { return m_Thunks.contains(thunk); } bool hasLib(QString libName); bool hasFunc(QString funcName); offset_t findThunk(QString libName, QString funcName); size_t countLibs() { return m_libs.size(); } size_t countImps() { return (m_Imports == NULL) ? 0 : m_Thunks.size(); } offset_t thunkAt(size_t impNum) { return impNum > m_Thunks.size() ? INVALID_ADDR : m_Thunks.at(impNum); } protected: void wrapFunctions(); bool addFunc(QString libName, QString funcName, offset_t thunk); QMap m_libs; FuncToThunk m_func; QList m_Thunks; ImportDirWrapper* m_Imports; }; ================================================ FILE: patcher/ImportsTableModel.cpp ================================================ #include "ImportsTableModel.h" #include #include QVariant ImportsTableModel::headerData(int section, Qt::Orientation orientation, int role) const { if (role != Qt::DisplayRole) return QVariant(); if (orientation != Qt::Horizontal) return QVariant(); switch (section) { case COL_THUNK : return "Thunk"; case COL_LIB : return "Lib"; case COL_FUNC : return "Functions"; case COL_REPLACEMENT : return "ReplacementFunction"; } return QVariant(); } Qt::ItemFlags ImportsTableModel::flags(const QModelIndex &index) const { if (!index.isValid()) return 0; Qt::ItemFlags f = Qt::ItemIsEnabled | Qt::ItemIsSelectable; if (index.column() == COL_REPLACEMENT) { f |= Qt::ItemIsEditable; } return f; } bool ImportsTableModel::setData(const QModelIndex &index, const QVariant &data, int role) { if (index.column() != COL_REPLACEMENT) { return false; } //TODO: put it in the controller? offset_t thunk = indexToFunctionThunk(index); QString substName = data.toString(); if (this->m_ExeHandler->m_Repl.getAt(thunk) == substName) return false; if (this->m_ExeHandler->defineReplacement(thunk, substName) == false) { QMessageBox::warning(NULL, "Error", "Invalid format supplied!\nValid: ."); return false; } return true; } QVariant ImportsTableModel::data(const QModelIndex &index, int role) const { if (this->countElements() == 0 || m_FuncMap == NULL) return QVariant(); offset_t thunk = indexToFunctionThunk(index); if (thunk == INVALID_ADDR) return QVariant(); if (role == Qt::UserRole) { return qint64(thunk); } if (role != Qt::DisplayRole && role != Qt::EditRole) return QVariant(); int attribute = index.column(); switch (attribute) { case COL_THUNK : return QString::number(thunk, 16); case COL_LIB : return m_FuncMap->thunkToLibName(thunk); case COL_FUNC : return m_FuncMap->thunkToFuncName(thunk); case COL_REPLACEMENT : { QString replName = this->m_ExeHandler->getReplAt(thunk); return replName; } } return QVariant(); } ================================================ FILE: patcher/ImportsTableModel.h ================================================ #pragma once #include #include #include "Executables.h" class ImportsTableModel : public QAbstractTableModel { Q_OBJECT public slots: void modelChanged() { this->beginResetModel(); this->endResetModel(); } public: enum COLS { COL_THUNK = 0, COL_LIB, COL_FUNC, COL_REPLACEMENT, COUNT_COL }; ImportsTableModel(QObject *v_parent) : QAbstractTableModel(v_parent), m_ExeHandler(NULL), m_FuncMap(NULL) {} virtual ~ImportsTableModel() { } QVariant headerData(int section, Qt::Orientation orientation, int role) const; Qt::ItemFlags flags(const QModelIndex &index) const; int columnCount(const QModelIndex &parent) const { return COUNT_COL; } int rowCount(const QModelIndex &parent) const { return countElements(); } QVariant data(const QModelIndex &index, int role) const; bool setData(const QModelIndex &, const QVariant &, int); QModelIndex index(int row, int column, const QModelIndex &parent = QModelIndex()) const { //no index item pointer return createIndex(row, column); } QModelIndex parent(const QModelIndex &index) const { return QModelIndex(); } // no parent public slots: void setExecutable(ExeHandler* exeHndl) { //> this->beginResetModel(); this->m_FuncMap = NULL; this->m_ExeHandler = exeHndl; if (this->m_ExeHandler) { this->m_FuncMap = &(m_ExeHandler->m_FuncMap); } this->endResetModel(); //< } protected slots: void onExeChanged() { //> this->beginResetModel(); this->endResetModel(); //< } protected: offset_t indexToFunctionThunk(const QModelIndex &index) const { if (index.isValid() == false) { return INVALID_ADDR; } int impNum = index.row(); size_t entriesCount = countElements(); if (entriesCount == 0 || impNum >= entriesCount) return INVALID_ADDR; offset_t thunk = this->m_FuncMap->thunkAt(impNum); //printf("Thunk = %llx (%x)\n", thunk, impNum); return thunk; } ExeHandler* m_ExeHandler; ImportsLookup *m_FuncMap; int countElements() const { return (m_FuncMap == NULL) ? 0 : m_FuncMap->countImps(); } }; ================================================ FILE: patcher/InfoTableModel.cpp ================================================ #include "InfoTableModel.h" #include "StubMaker.h" #include #include #define HIGLIHHT_COLOR "yellow" #define OK_COLOR "green" #define NOT_OK_COLOR "red" QVariant InfoTableModel::headerData(int section, Qt::Orientation orientation, int role) const { if (role != Qt::DisplayRole) return QVariant(); if (orientation != Qt::Horizontal) return QVariant(); switch (section) { case COL_NAME : return "FileName"; case COL_HOOKED: return "Hooked?"; case COL_RAW_SIZE: return "RawSize"; case COL_VIRTUAL_SIZE: return "VirtualSize"; case COL_SECNUM : return "Sections"; case COL_IMPNUM : return "Imports"; } return QVariant(); } Qt::ItemFlags InfoTableModel::flags(const QModelIndex &index) const { if (!index.isValid()) return 0; Qt::ItemFlags f = Qt::ItemIsEnabled | Qt::ItemIsSelectable; if (index.column() == COL_HOOKED) { f |= Qt::ItemIsUserCheckable; f |= Qt::ItemIsEditable; } return f; } bool InfoTableModel::setData(const QModelIndex &index, const QVariant &, int role) { if (index.column() == COL_HOOKED) { if ( role == Qt::CheckStateRole) { int id = index.row(); if (m_Exes == NULL) return false; emit hookRequested(this->m_Exes->at(id)); } return true; } return false; } QVariant InfoTableModel::data(const QModelIndex &index, int role) const { int elNum = index.row(); if (elNum > countElements()) return QVariant(); int attribute = index.column(); if (attribute >= COUNT_COL) return QVariant(); if (role == Qt::UserRole) { return uint(elNum); } ExeHandler *exeHndl = m_Exes->at(elNum); if (exeHndl == NULL) return QVariant(); Executable *exe = exeHndl->getExe(); if (exe == NULL) return QVariant(); if (role == Qt::DisplayRole) { return getDisplayData(role, attribute, exeHndl); } if (role == Qt::BackgroundColorRole) { if (exeHndl->getUnappliedState() == true) { return QColor(HIGLIHHT_COLOR); } return QVariant(); } if (role == Qt::DecorationRole && attribute == COL_NAME) { if (exe->isBit32()) return QIcon(":/icons/app32.ico"); if (exe->isBit64()) return QIcon(":/icons/app64.ico"); } if (role == Qt::CheckStateRole && attribute == COL_HOOKED) { if (exeHndl->getHookedState()) return Qt::Checked; else return Qt::Unchecked; } PEFile *pe = dynamic_cast(exeHndl->getExe()); if (pe == NULL) return QVariant(); if (role == Qt::TextColorRole ) { if (attribute == COL_SECNUM) { if (pe->canAddNewSection()) return QColor(OK_COLOR); return QColor(NOT_OK_COLOR); } if (attribute == COL_IMPNUM) { if (StubMaker::countMissingImports(exeHndl) > 0) return QColor(NOT_OK_COLOR); return QColor(OK_COLOR); } return QVariant(); } if (role == Qt::ToolTipRole ) { if (attribute == COL_SECNUM) { if (pe->canAddNewSection()) return "Can add section"; return "Can NOT add section"; } if (attribute == COL_IMPNUM) { if (StubMaker::countMissingImports(exeHndl) > 0) return "Needs to add imports"; return "Can reuse all imports"; } if (attribute == COL_HOOKED) { QString info = exeHndl->getHookedState() ? "Hooked": "Not hooked"; info += "\nDefined "+ QString::number(exeHndl->m_Repl.size()) + " replacements"; return info; } if (attribute == COL_NAME) { QString epInfo = "OEP\t= "+ QString::number( exeHndl->getOriginalEP(), 16 ); if (exeHndl->getHookedState()) { epInfo += "\nEP \t= "+ QString::number( exeHndl->getCurrentEP(), 16 ); } return epInfo; } return ""; } return QVariant(); } QVariant InfoTableModel::getDisplayData(int role, int attribute, ExeHandler *exeHndl) const { Executable *exe = exeHndl->getExe(); if (exe == NULL) return QVariant(); if (role != Qt::DisplayRole) return QVariant(); switch (attribute) { case COL_NAME : { QFileInfo inputInfo(exeHndl->getFileName()); QString name = inputInfo.fileName(); if (exeHndl->getModifiedState() == true) { name = "* " + name; } return name; } case COL_RAW_SIZE : return exe->getMappedSize(Executable::RAW); case COL_VIRTUAL_SIZE : return exe->getMappedSize(Executable::RVA); } PEFile *pe = dynamic_cast(exeHndl->getExe()); if (pe == NULL) return QVariant(); switch (attribute) { case COL_SECNUM : return qint64(pe->hdrSectionsNum()); case COL_IMPNUM : { ExeNodeWrapper *wr = dynamic_cast(pe->getWrapper(PEFile::WR_DIR_ENTRY + pe::DIR_IMPORT)); if (!wr) return 0; return qint64(wr->getEntriesCount()); } case COL_HOOKED : { return qint64(exeHndl->m_Repl.size()); } } return QVariant(); } ================================================ FILE: patcher/InfoTableModel.h ================================================ #pragma once #include #include "Executables.h" #include class InfoTableModel : public QAbstractTableModel { Q_OBJECT signals: void hookRequested(ExeHandler* exe); public slots: void modelChanged() { //> this->beginResetModel(); this->endResetModel(); //< } public: enum COLS { COL_NAME = 0, COL_HOOKED, COL_RAW_SIZE, COL_VIRTUAL_SIZE, COL_SECNUM, COL_IMPNUM, COUNT_COL }; InfoTableModel(QObject *v_parent) : QAbstractTableModel(v_parent), m_Exes(NULL) {} virtual ~InfoTableModel() { } QVariant headerData(int section, Qt::Orientation orientation, int role) const; Qt::ItemFlags flags(const QModelIndex &index) const; int columnCount(const QModelIndex &parent) const { return COUNT_COL; } int rowCount(const QModelIndex &parent) const { return countElements(); } QVariant data(const QModelIndex &index, int role) const; bool setData(const QModelIndex &, const QVariant &, int); QModelIndex index(int row, int column, const QModelIndex &parent = QModelIndex()) const { //no index item pointer return createIndex(row, column); } QModelIndex parent(const QModelIndex &index) const { return QModelIndex(); } // no parent public slots: void setExecutables(Executables *exes) { //> this->beginResetModel(); if (this->m_Exes != NULL) { //disconnect old QObject::disconnect(this->m_Exes, SIGNAL(exeListChanged()), this, SLOT( onExeListChanged() ) ); } this->m_Exes = exes; if (this->m_Exes != NULL) { QObject::connect(this->m_Exes, SIGNAL(exeListChanged()), this, SLOT( onExeListChanged() ) ); } this->endResetModel(); //< } protected slots: void onExeListChanged() { //> this->beginResetModel(); this->endResetModel(); //< } protected: Executables* m_Exes; QVariant getDisplayData(int role, int attribute, ExeHandler *exeHndl) const; int countElements() const { return (m_Exes == NULL)? 0: m_Exes->size(); } }; ================================================ FILE: patcher/LICENSE ================================================ GNU GENERAL PUBLIC LICENSE Version 2, June 1991 Copyright (C) 1989, 1991 Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble The licenses for most software are designed to take away your freedom to share and change it. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change free software--to make sure the software is free for all its users. This General Public License applies to most of the Free Software Foundation's software and to any other program whose authors commit to using it. (Some other Free Software Foundation software is covered by the GNU Lesser General Public License instead.) You can apply it to your programs, too. When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for this service if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs; and that you know you can do these things. To protect your rights, we need to make restrictions that forbid anyone to deny you these rights or to ask you to surrender the rights. These restrictions translate to certain responsibilities for you if you distribute copies of the software, or if you modify it. For example, if you distribute copies of such a program, whether gratis or for a fee, you must give the recipients all the rights that you have. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights. We protect your rights with two steps: (1) copyright the software, and (2) offer you this license which gives you legal permission to copy, distribute and/or modify the software. Also, for each author's protection and ours, we want to make certain that everyone understands that there is no warranty for this free software. If the software is modified by someone else and passed on, we want its recipients to know that what they have is not the original, so that any problems introduced by others will not reflect on the original authors' reputations. Finally, any free program is threatened constantly by software patents. We wish to avoid the danger that redistributors of a free program will individually obtain patent licenses, in effect making the program proprietary. To prevent this, we have made it clear that any patent must be licensed for everyone's free use or not licensed at all. The precise terms and conditions for copying, distribution and modification follow. GNU GENERAL PUBLIC LICENSE TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 0. This License applies to any program or other work which contains a notice placed by the copyright holder saying it may be distributed under the terms of this General Public License. The "Program", below, refers to any such program or work, and a "work based on the Program" means either the Program or any derivative work under copyright law: that is to say, a work containing the Program or a portion of it, either verbatim or with modifications and/or translated into another language. (Hereinafter, translation is included without limitation in the term "modification".) Each licensee is addressed as "you". Activities other than copying, distribution and modification are not covered by this License; they are outside its scope. The act of running the Program is not restricted, and the output from the Program is covered only if its contents constitute a work based on the Program (independent of having been made by running the Program). Whether that is true depends on what the Program does. 1. You may copy and distribute verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice and disclaimer of warranty; keep intact all the notices that refer to this License and to the absence of any warranty; and give any other recipients of the Program a copy of this License along with the Program. You may charge a fee for the physical act of transferring a copy, and you may at your option offer warranty protection in exchange for a fee. 2. You may modify your copy or copies of the Program or any portion of it, thus forming a work based on the Program, and copy and distribute such modifications or work under the terms of Section 1 above, provided that you also meet all of these conditions: a) You must cause the modified files to carry prominent notices stating that you changed the files and the date of any change. b) You must cause any work that you distribute or publish, that in whole or in part contains or is derived from the Program or any part thereof, to be licensed as a whole at no charge to all third parties under the terms of this License. c) If the modified program normally reads commands interactively when run, you must cause it, when started running for such interactive use in the most ordinary way, to print or display an announcement including an appropriate copyright notice and a notice that there is no warranty (or else, saying that you provide a warranty) and that users may redistribute the program under these conditions, and telling the user how to view a copy of this License. (Exception: if the Program itself is interactive but does not normally print such an announcement, your work based on the Program is not required to print an announcement.) These requirements apply to the modified work as a whole. If identifiable sections of that work are not derived from the Program, and can be reasonably considered independent and separate works in themselves, then this License, and its terms, do not apply to those sections when you distribute them as separate works. But when you distribute the same sections as part of a whole which is a work based on the Program, the distribution of the whole must be on the terms of this License, whose permissions for other licensees extend to the entire whole, and thus to each and every part regardless of who wrote it. Thus, it is not the intent of this section to claim rights or contest your rights to work written entirely by you; rather, the intent is to exercise the right to control the distribution of derivative or collective works based on the Program. In addition, mere aggregation of another work not based on the Program with the Program (or with a work based on the Program) on a volume of a storage or distribution medium does not bring the other work under the scope of this License. 3. You may copy and distribute the Program (or a work based on it, under Section 2) in object code or executable form under the terms of Sections 1 and 2 above provided that you also do one of the following: a) Accompany it with the complete corresponding machine-readable source code, which must be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange; or, b) Accompany it with a written offer, valid for at least three years, to give any third party, for a charge no more than your cost of physically performing source distribution, a complete machine-readable copy of the corresponding source code, to be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange; or, c) Accompany it with the information you received as to the offer to distribute corresponding source code. (This alternative is allowed only for noncommercial distribution and only if you received the program in object code or executable form with such an offer, in accord with Subsection b above.) The source code for a work means the preferred form of the work for making modifications to it. For an executable work, complete source code means all the source code for all modules it contains, plus any associated interface definition files, plus the scripts used to control compilation and installation of the executable. However, as a special exception, the source code distributed need not include anything that is normally distributed (in either source or binary form) with the major components (compiler, kernel, and so on) of the operating system on which the executable runs, unless that component itself accompanies the executable. If distribution of executable or object code is made by offering access to copy from a designated place, then offering equivalent access to copy the source code from the same place counts as distribution of the source code, even though third parties are not compelled to copy the source along with the object code. 4. You may not copy, modify, sublicense, or distribute the Program except as expressly provided under this License. Any attempt otherwise to copy, modify, sublicense or distribute the Program is void, and will automatically terminate your rights under this License. However, parties who have received copies, or rights, from you under this License will not have their licenses terminated so long as such parties remain in full compliance. 5. You are not required to accept this License, since you have not signed it. However, nothing else grants you permission to modify or distribute the Program or its derivative works. These actions are prohibited by law if you do not accept this License. Therefore, by modifying or distributing the Program (or any work based on the Program), you indicate your acceptance of this License to do so, and all its terms and conditions for copying, distributing or modifying the Program or works based on it. 6. Each time you redistribute the Program (or any work based on the Program), the recipient automatically receives a license from the original licensor to copy, distribute or modify the Program subject to these terms and conditions. You may not impose any further restrictions on the recipients' exercise of the rights granted herein. You are not responsible for enforcing compliance by third parties to this License. 7. If, as a consequence of a court judgment or allegation of patent infringement or for any other reason (not limited to patent issues), conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot distribute so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not distribute the Program at all. For example, if a patent license would not permit royalty-free redistribution of the Program by all those who receive copies directly or indirectly through you, then the only way you could satisfy both it and this License would be to refrain entirely from distribution of the Program. If any portion of this section is held invalid or unenforceable under any particular circumstance, the balance of the section is intended to apply and the section as a whole is intended to apply in other circumstances. It is not the purpose of this section to induce you to infringe any patents or other property right claims or to contest validity of any such claims; this section has the sole purpose of protecting the integrity of the free software distribution system, which is implemented by public license practices. Many people have made generous contributions to the wide range of software distributed through that system in reliance on consistent application of that system; it is up to the author/donor to decide if he or she is willing to distribute software through any other system and a licensee cannot impose that choice. This section is intended to make thoroughly clear what is believed to be a consequence of the rest of this License. 8. If the distribution and/or use of the Program is restricted in certain countries either by patents or by copyrighted interfaces, the original copyright holder who places the Program under this License may add an explicit geographical distribution limitation excluding those countries, so that distribution is permitted only in or among countries not thus excluded. In such case, this License incorporates the limitation as if written in the body of this License. 9. The Free Software Foundation may publish revised and/or new versions of the General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Program specifies a version number of this License which applies to it and "any later version", you have the option of following the terms and conditions either of that version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of this License, you may choose any version ever published by the Free Software Foundation. 10. If you wish to incorporate parts of the Program into other free programs whose distribution conditions are different, write to the author to ask for permission. For software which is copyrighted by the Free Software Foundation, write to the Free Software Foundation; we sometimes make exceptions for this. Our decision will be guided by the two goals of preserving the free status of all derivatives of our free software and of promoting the sharing and reuse of software generally. NO WARRANTY 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. END OF TERMS AND CONDITIONS How to Apply These Terms to Your New Programs If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms. To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively convey the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. {description} Copyright (C) {year} {fullname} This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. Also add information on how to contact you by electronic and paper mail. If the program is interactive, make it output a short notice like this when it starts in an interactive mode: Gnomovision version 69, Copyright (C) year name of author Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details. The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, the commands you use may be called something other than `show w' and `show c'; they could even be mouse-clicks or menu items--whatever suits your program. You should also get your employer (if you work as a programmer) or your school, if any, to sign a "copyright disclaimer" for the program, if necessary. Here is a sample; alter the names: Yoyodyne, Inc., hereby disclaims all copyright interest in the program `Gnomovision' (which makes passes at compilers) written by James Hacker. {signature of Ty Coon}, 1 April 1989 Ty Coon, President of Vice This General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Lesser General Public License instead of this License. ================================================ FILE: patcher/README.md ================================================ IAT patcher ============ Main application source. ================================================ FILE: patcher/ReplacementsDialog.cpp ================================================ #include "ReplacementsDialog.h" ReplacementsDialog::ReplacementsDialog(QWidget *parent) : QDialog(parent) { this->m_uiReplacements = new Ui_Replacements(); this->m_uiReplacements->setupUi(this); setAcceptDrops(true); m_libsModel = new LibsModel(this->m_uiReplacements->libraryCombo); m_functModel = new FunctionsModel(this->m_uiReplacements->functionCombo); this->m_uiReplacements->libraryCombo->setModel(m_libsModel); this->m_uiReplacements->functionCombo->setModel(m_functModel); m_libsModel->setLibraries(&m_libInfos); m_functModel->setLibraries(&m_libInfos); connect(this->m_uiReplacements->okCancel_buttons, SIGNAL(rejected()), this, SLOT(hide())); connect(this->m_uiReplacements->okCancel_buttons, SIGNAL(accepted()), this, SLOT(requestReplacement())); connect(m_uiReplacements->addLibraryButton, SIGNAL(clicked()), this, SLOT(openLibrary())); connect(m_uiReplacements->libraryCombo, SIGNAL(currentIndexChanged(int)), m_functModel, SLOT(on_currentndexChanged(int))); connect(this, SIGNAL(parseLibrary(QString&)), &m_libParser, SLOT(on_parseLibrary(QString&)) ); connect(&m_libParser, SIGNAL(infoCreated(LibraryInfo*)), &m_libInfos, SLOT(addElement(LibraryInfo *)) ); } void ReplacementsDialog::displayFuncToReplace(offset_t thunk, QString libName, QString funcName) { this->m_uiReplacements->thunkLabel->setText(QString::number(thunk, 16)); this->m_uiReplacements->libToReplaceLabel->setText(libName+"."+funcName); } void ReplacementsDialog::displayReplacement(QString libName, QString funcName) { this->m_uiReplacements->libraryEdit->setText(libName); this->m_uiReplacements->functionEdit->setText(funcName); } void ReplacementsDialog::displayReplacement(FuncDesc &desc) { QString libName; QString funcName; FuncUtil::parseFuncDesc(desc, libName, funcName); this->displayReplacement(libName, funcName); } QString ReplacementsDialog::getLibName() { int tabNum = this->m_uiReplacements->tabWidget->currentIndex(); switch (tabNum) { case TAB_EDIT : return this->m_uiReplacements->libraryEdit->text(); case TAB_CHOSE : return this->m_uiReplacements->libraryCombo->currentText(); } return ""; } QString ReplacementsDialog::getFuncName() { int tabNum = this->m_uiReplacements->tabWidget->currentIndex(); switch (tabNum) { case TAB_EDIT : return this->m_uiReplacements->functionEdit->text(); case TAB_CHOSE : return this->m_uiReplacements->functionCombo->currentText(); } return ""; } void ReplacementsDialog::openLibrary() { QString fileName = QFileDialog::getOpenFileName( this, tr("Open executable"), QDir::homePath(), "DLL Files (*.dll);;All files (*)" ); if (fileName != "") { emit parseLibrary(fileName); } } void ReplacementsDialog::requestReplacement() { emit setReplacement(getLibName(), getFuncName()); } void ReplacementsDialog::dragEnterEvent(QDragEnterEvent *event) { event->accept(); } void ReplacementsDialog::dropEvent(QDropEvent* ev) { this->m_uiReplacements->tabWidget->setCurrentIndex(TAB_CHOSE); QList urls = ev->mimeData()->urls(); QList::Iterator urlItr; QCursor cur = this->cursor(); this->setCursor(Qt::BusyCursor); for (urlItr = urls.begin() ; urlItr != urls.end(); urlItr++) { QString fileName = urlItr->toLocalFile(); if (fileName == "") continue; emit parseLibrary(fileName); } this->setCursor(cur); } ================================================ FILE: patcher/ReplacementsDialog.h ================================================ #pragma once #include #include #include #include "Executables.h" #include "ui_replacements.h" #include "dllparse/LibraryParser.h" #include "dllparse/LibsModel.h" #include "dllparse/FunctionsModel.h" class ReplacementsDialog : public QDialog { Q_OBJECT signals: void setReplacement(QString libName, QString funcName); void parseLibrary(QString &path); public: enum TABS { TAB_EDIT = 0, TAB_CHOSE = 1, COUNT_TABS }; explicit ReplacementsDialog(QWidget *parent = 0); ~ReplacementsDialog() { } void displayFuncToReplace(offset_t thunk, QString libName, QString funcName); void displayReplacement(QString libName, QString funcName); void displayReplacement(FuncDesc &desc); QString getLibName(); QString getFuncName(); /* events */ void dragEnterEvent(QDragEnterEvent *ev); void dropEvent(QDropEvent* ev); private slots: void requestReplacement(); void openLibrary(); private: Ui_Replacements* m_uiReplacements; LibsModel *m_libsModel; FunctionsModel *m_functModel; LibInfos m_libInfos; LibraryParser m_libParser; }; ================================================ FILE: patcher/StubMaker.cpp ================================================ #include "StubMaker.h" #include "stub/Stub32.h" #include "stub/Stub64.h" const size_t SEC_PADDING = 10; size_t StubMaker::countMissingImports(ImportsLookup &funcMap) { QString libName = "Kernel32.dll"; QStringList funcNames = (QStringList() << "LoadLibraryA" << "GetProcAddress"); // << "VirtualProtect" size_t count = 0; for ( size_t i = 0; i < funcNames.size(); i++) { offset_t thunk = funcMap.findThunk(libName, funcNames[i]); if (thunk == INVALID_ADDR) { count++; } } return count; } bool StubMaker::fillHookedInfo(ExeHandler *exeHndl) { if (exeHndl == NULL) return false; PEFile *pe = static_cast (exeHndl->getExe()); if (pe == NULL) return false; offset_t ep = pe->getEntryPoint(); offset_t epRaw = pe->convertAddr(ep, Executable::RVA, Executable::RAW); if (epRaw == INVALID_ADDR) return false; BufferView epView(pe, epRaw, pe->getContentSize() - epRaw); Stub *stub = NULL; if (pe->isBit32()) { stub = new Stub32(); } else { stub = new Stub64(); } bool isContained = stub->containsStub(&epView); exeHndl->setHookedState(isContained); if (isContained) { if (stub->readParams(&epView)) { //TODO: fill all the params in exeHndl /*size_t pCnt = stub->getParamsCount(); for (size_t id = 0; id< pCnt; id++) { printf("[%d] = %llx\n", id, stub->getParamValue(id)); }*/ //TODO: keep stub params in a separate structure exeHndl->originalEP = stub->getParamValue(Stub::OEP); exeHndl->dataStoreRva = stub->getParamValue(Stub::DATA_RVA); offset_t dataRva =exeHndl->dataStoreRva; offset_t dataRaw = pe->toRaw(dataRva, Executable::RVA); BufferView dataBuf(pe, dataRaw, pe->getContentSize() - dataRaw); //printf("Reading dataStore at = %llx -> %llx\n", dataRva, dataRaw); readDataStore(&dataBuf, dataRva, exeHndl->m_Repl); //printf("Params OK, OEP = %llx\n", exeHndl->originalEP); } } delete stub; return isContained; } Stub* StubMaker::makeStub(PEFile *pe) { if (pe == NULL) return NULL; Stub *stb = NULL; if (pe->isBit32()) { stb = new Stub32(); } else { stb = new Stub64(); } return stb; } bool StubMaker::setStubParams(Stub* stb, PEFile *pe, const offset_t newEntry, const offset_t dataRva, ImportsLookup &funcMap) { offset_t loadLib = funcMap.findThunk("Kernel32.dll","LoadLibraryA"); offset_t getProc = funcMap.findThunk("Kernel32.dll","GetProcAddress"); offset_t oldEntry = pe->getEntryPoint(); stb->setParam(Stub::NEW_EP, newEntry); stb->setParam(Stub::OEP, oldEntry); stb->setParam(Stub::DATA_RVA, dataRva); stb->setParam(Stub::FUNC_LOAD_LIB_RVA, loadLib); stb->setParam(Stub::FUNC_GET_MODULE_RVA, getProc); return true; } size_t StubMaker::calcReplNamesSize(FuncReplacements &funcRepl) { const size_t PADDING = 1; size_t requiredLen = PADDING; QList thunks = funcRepl.getThunks(); QList::Iterator itr; for (itr = thunks.begin(); itr != thunks.end(); itr++) { FuncDesc desc = funcRepl.getAt(*itr); requiredLen += desc.size(); requiredLen += PADDING; } return requiredLen; } size_t StubMaker::calcDataStoreSize(FuncReplacements &funcRepl) { const size_t ELEMENTS = 4; //libRVA, funcRVA, thunk, EMPTY const size_t OFFSETS_SPACE = (funcRepl.size() * ELEMENTS * sizeof(DWORD)) + sizeof(DWORD) * 2; const size_t NAMES_SPACE = calcReplNamesSize(funcRepl); const size_t TOTAL_SPACE = OFFSETS_SPACE + NAMES_SPACE; return TOTAL_SPACE; } ByteBuffer* StubMaker::makeDataStore(const offset_t dataRva, FuncReplacements &funcRepl) { const size_t ELEMENTS = 4; //libRVA, funcRVA, thunk, EMPTY const size_t OFFSETS_SPACE = (funcRepl.size() * ELEMENTS * sizeof(DWORD)) + sizeof(DWORD) * 2; const size_t NAMES_SPACE = calcReplNamesSize(funcRepl); const size_t TOTAL_SPACE = OFFSETS_SPACE + NAMES_SPACE; char *buffer = new char[TOTAL_SPACE]; memset(buffer, 0, TOTAL_SPACE); size_t DELTA1 = OFFSETS_SPACE; char* namesBuf = &buffer[DELTA1]; DWORD nameRva = dataRva + DELTA1; QList allThunks = funcRepl.getThunks(); DWORD *fAddress = (DWORD*) buffer; size_t addrIndx = 0; for (int i = 0; i < allThunks.size(); i++) { offset_t thunk = allThunks[i]; FuncDesc library = funcRepl.getAt(thunk); QString libName; QString funcName; if (FuncUtil::parseFuncDesc(library, libName, funcName) == false) { //printf("Invalid library format!\n"); continue; } strcpy(namesBuf, libName.toStdString().c_str()); fAddress[addrIndx++] = nameRva; size_t libLen = libName.length() + 1; nameRva += libLen; namesBuf += libLen; strcpy(namesBuf, funcName.toStdString().c_str()); fAddress[addrIndx++] = nameRva; size_t funcLen = funcName.length() + 1; nameRva += funcLen; namesBuf += funcLen; //save thunk: fAddress[addrIndx++] = thunk; //add space: fAddress[addrIndx++] = 0; } ByteBuffer *dataBuf = new ByteBuffer((BYTE*) buffer, TOTAL_SPACE, 0); delete []buffer; return dataBuf; } bool StubMaker::readDataStore(AbstractByteBuffer* buf, const offset_t dataRva, FuncReplacements &funcRepl) { const offset_t start = dataRva; const size_t unitSize = sizeof(DWORD); offset_t valOffset = 0; offset_t value = 0; bool isOk = true; for (valOffset = 0; isOk ;) { value = buf->getNumValue(valOffset, unitSize, &isOk); valOffset += unitSize; if (!isOk || value == 0) break; offset_t dllNameOffset = value - start; QString dllName = buf->getStringValue(dllNameOffset); while (isOk) { value = buf->getNumValue(valOffset, unitSize, &isOk); valOffset += unitSize; offset_t funcNameOffset = value - start; if (!isOk || value == 0) break; //end of DLL processing value = buf->getNumValue(valOffset, unitSize, &isOk); valOffset += unitSize; if (!isOk || value == 0) break; //end of DLL processing offset_t thunk = value; QString funcName = buf->getStringValue(funcNameOffset); //TODO: refactor it... FuncDesc desc = dllName + "." + funcName; funcRepl.defineReplacement(thunk, desc); } } return isOk; } bool StubMaker::overwriteDataStore(ExeHandler *exeHndl) { if (exeHndl->isHooked == false) return false; PEFile *pe = dynamic_cast(exeHndl->getExe()); if (!pe) return false; offset_t dataRva = exeHndl->dataStoreRva; offset_t dataRaw = pe->toRaw(dataRva, Executable::RVA); if (dataRaw == INVALID_ADDR || dataRaw == 0) return false; bufsize_t currentSize = pe->getContentSize() - dataRaw; bufsize_t requiredSize = calcDataStoreSize(exeHndl->m_Repl); if (requiredSize > currentSize) { bufsize_t dif = requiredSize - currentSize; //perform resising... if (!pe->extendLastSection(dif + SEC_PADDING)) return false; } BufferView dataBuf(pe, dataRaw, pe->getContentSize() - dataRaw); dataBuf.fillContent(0); ByteBuffer* newStore = makeDataStore(dataRva, exeHndl->m_Repl); bool isOk = dataBuf.pasteBuffer(0, newStore, false); delete newStore; return isOk; } bool StubMaker::addFunction(PEFile *pe, ImportEntryWrapper* libWr, ImportedFuncWrapper* func, const QString& name, offset_t &storageOffset) { if (pe == NULL) return false; ImportedFuncWrapper* fWr = dynamic_cast(libWr->addEntry(func)); if (fWr == NULL) { printf("Cannot add function\n"); return false; } offset_t thunkRVA = pe->convertAddr(storageOffset, Executable::RAW, Executable::RVA); fWr->setNumValue(ImportedFuncWrapper::THUNK, thunkRVA); fWr->setNumValue(ImportedFuncWrapper::ORIG_THUNK, thunkRVA); storageOffset += sizeof(WORD); //add sizeof Hint if (pe->setStringValue(storageOffset, name) == false) { printf("Failed to fill lib name\n"); return false; } storageOffset += name.length() + 1; return true; } ImportEntryWrapper* StubMaker::addLibrary(PEFile *pe, QString name, offset_t &storageOffset) { //add new library wrapper: ImportDirWrapper* imports = dynamic_cast (pe->getWrapper(PEFile::WR_DIR_ENTRY + pe::DIR_IMPORT)); ImportEntryWrapper* libWr = dynamic_cast (imports->addEntry(NULL)); if (libWr == NULL) return NULL; const size_t PADDING = libWr->getSize(); storageOffset = imports->getOffset() + imports->getContentSize() + PADDING; offset_t nameOffset = storageOffset; if (pe->setStringValue(storageOffset, name) == false) { printf("Failed to fill lib name\n"); return NULL; } storageOffset += name.length() + PADDING; offset_t firstThunk = pe->convertAddr(storageOffset, Executable::RAW, Executable::RVA); libWr->setNumValue(ImportEntryWrapper::FIRST_THUNK, firstThunk); libWr->setNumValue(ImportEntryWrapper::ORIG_FIRST_THUNK, firstThunk); libWr->wrap(); storageOffset += PADDING; offset_t nameRva = pe->convertAddr(nameOffset, Executable::RAW, Executable::RVA); libWr->setNumValue(ImportEntryWrapper::NAME, nameRva); return libWr; } bool StubMaker::addMissingFunctions(PEFile *pe, ImportsLookup &funcMap, bool tryReuse) { offset_t storageOffset = 0; QString library = "Kernel32.dll"; ImportEntryWrapper* libWr = addLibrary(pe, library, storageOffset); if (libWr == NULL) { //printf("Adding library failed!\n"); return false; } ImportDirWrapper* imports = dynamic_cast (pe->getWrapper(PEFile::WR_DIR_ENTRY + pe::DIR_IMPORT)); if (imports == NULL) { printf("Cannot fetch imports!\n"); return false; } //TODO: add missing without relying on previous... size_t prevEntry = imports->getEntriesCount() - 2; ImportEntryWrapper* prevWr = dynamic_cast (imports->getEntryAt(prevEntry)); if (prevWr == NULL) return false; size_t prevWrCount = prevWr->getEntriesCount(); if (prevWrCount == 0) { return false; } ImportedFuncWrapper* prevLast = dynamic_cast (prevWr->getEntryAt(prevWrCount - 1)); if (prevLast == NULL) return false; //---- const size_t fNum = 2; const QString fNames[] = {"LoadLibraryA", "GetProcAddress" }; size_t entrySize = prevLast->getSize(); storageOffset += (fNum + 1) * entrySize; bool isOk = true; for ( size_t i = 0; i < fNum; i++) { if (tryReuse && funcMap.findThunk(library, fNames[i]) != INVALID_ADDR) { //Function exist, no need to add... continue; } if (addFunction(pe, libWr, prevLast, fNames[i], storageOffset) == false) { isOk = false; break; } } imports->reloadMapping(); return isOk; } bool StubMaker::makeThunksWriteable(PEFile *pe, FuncReplacements* funcRepl) { ImportDirWrapper* imps = dynamic_cast( pe->getDataDirEntry(pe::DIR_IMPORT)); if (imps == NULL) return false; QList thunks = (funcRepl) ? funcRepl->getThunks() : imps->getThunksList(); //TODO: optimize it for (size_t i = 0; i < thunks.size(); i++) { offset_t thunk = thunks[i]; SectionHdrWrapper *sHdr = pe->getSecHdrAtOffset(thunk, Executable::RVA, true); if (sHdr == NULL) continue; DWORD oldCharact = sHdr->getCharacteristics(); sHdr->setCharacteristics(oldCharact | 0xC0000000); } return true; } size_t StubMaker::calcNewImportsSize(PEFile *pe, size_t addedFuncCount) { ImportDirWrapper* imports = dynamic_cast (pe->getWrapper(PEFile::WR_DIR_ENTRY + pe::DIR_IMPORT)); IMAGE_DATA_DIRECTORY* ddir = pe->getDataDirectory(); size_t impDirSize = ddir[pe::DIR_IMPORT].Size; size_t impSize = imports->getContentSize(); if (impDirSize > impSize) impSize = impDirSize; size_t impNewSize = impSize; impNewSize += sizeof(IMAGE_IMPORT_DESCRIPTOR) * (addedFuncCount + 1); //append new functions + one as padding return impNewSize; } bool StubMaker::makeStub(PEFile *pe, ImportsLookup &funcMap, FuncReplacements &funcRepl, const StubSettings &settings) { try { if (pe == NULL) { return false; } ExeNodeWrapper* sec = dynamic_cast(pe->getWrapper(PEFile::WR_SECTIONS)); if (sec == NULL) { return false; } bufsize_t startOffset = 0; bufsize_t stubOffset = 0; bufsize_t TABLE_PADDING = 0x100; Stub* stb = StubMaker::makeStub(pe); size_t stubSize = stb->getSize(); bufsize_t stubSectionSize = StubMaker::calcDataStoreSize(funcRepl) + stubSize + TABLE_PADDING; bool mustRewriteImports = false; size_t missingCount = StubMaker::countMissingImports(funcMap); //Check if adding imports is required if ( missingCount != 0 || (settings.reuseImports == false)) { //TODO: try to add to existing lib... //TODO: if failed: try to add to existing Import Table... //if failed: include import dir in the new section size... mustRewriteImports = true; stubOffset = calcNewImportsSize(pe, missingCount) + TABLE_PADDING; stubSectionSize += stubOffset; } SectionHdrWrapper *stubHdr = NULL; if (settings.getAddNewSection() && pe->canAddNewSection()) { stubHdr = pe->addNewSection("stub", stubSectionSize); if (!stubHdr) { printf("Failed adding section...\n"); } } if (stubHdr == NULL) { stubHdr = pe->getLastSection(); if (stubHdr == NULL) { printf("Cannot fetch last section!\n"); return false; } // resize section offset_t secROffset = stubHdr->getContentOffset(Executable::RAW, true); startOffset = pe->getContentSize() - secROffset; startOffset += SEC_PADDING; stubHdr = pe->extendLastSection(stubSectionSize + SEC_PADDING); if (stubHdr == NULL) { printf("Cannot fetch last section!\n"); return false; } } DWORD oldCharact = stubHdr->getCharacteristics(); stubHdr->setCharacteristics(oldCharact | 0xE0000000); stubOffset += startOffset; //fetch again after modification... sec = dynamic_cast(pe->getWrapper(PEFile::WR_SECTIONS)); if (sec == NULL) { printf("Cannot fetch sections wrapper\n"); return false; } size_t stubSecId = sec->getEntriesCount() - 1; //printf("Last section: %d\n", stubSecId); const offset_t SEC_RVA = stubHdr->getContentOffset(Executable::RVA); //printf("Last sectiont RVA = %llx\n", SEC_RVA ); const offset_t START_RVA = SEC_RVA + startOffset; //printf("Start writing at : %llx\n", START_RVA ); if (mustRewriteImports) { bool added = false; try { if (pe->moveDataDirEntry(pe::DIR_IMPORT, START_RVA, Executable::RVA)) { added = addMissingFunctions(pe, funcMap, settings.reuseImports); if (added == false) { printf("Unable to add all the required functions!\n"); return false; } makeThunksWriteable(pe); added = true; } } catch (ExeException &e) { printf("Not moved, because: %s\n", e.what()); } if (!added) { printf("Unable to add all the required functions#2\n"); return false; } } pe->unbindImports(); ImportDirWrapper* imps = dynamic_cast( pe->getDataDirEntry(pe::DIR_IMPORT)); funcMap.wrap(imps); BufferView* stubSecView = pe->createSectionView(stubSecId); if (stubSecView == NULL) { return false; } size_t DATA_OFFSET = stubOffset + stubSize; offset_t dataRva = SEC_RVA + stubOffset + stubSize; offset_t newEntryPoint = SEC_RVA + stubOffset; ByteBuffer* dataStore = StubMaker::makeDataStore(dataRva, funcRepl); if (StubMaker::setStubParams(stb, pe, newEntryPoint, dataRva, funcMap) == false) { printf("Making stub failed: loaderStub == NULL\n"); } ByteBuffer *loaderStub = stb->createStubBuffer(); delete stb; stb = NULL; bool hasAdded = false; if (stubSecView->pasteBuffer(stubOffset, loaderStub, false)) { pe->setEntryPoint(newEntryPoint, Executable::RVA); hasAdded = true; } else { printf("pasting buffer failed!\n"); } if (hasAdded) { if (stubSecView->pasteBuffer(DATA_OFFSET, dataStore, false)) { printf("pasted data"); hasAdded = true; } } delete loaderStub; delete dataStore; delete stubSecView; return hasAdded; } catch (CustomException &e) { printf ("Not added, because: %s\n", e.what()); } return false; } ================================================ FILE: patcher/StubMaker.h ================================================ #pragma once #include #include "Executables.h" #include "FuncReplacements.h" #include "stub/Stub.h" class StubSettings : public QObject { Q_OBJECT public: StubSettings() : addNewSection(true), reuseImports(true) {} void setAddNewSection(bool isEnabled) { this->addNewSection = isEnabled; } void setReuseImports(bool isEnabled) { this->reuseImports = isEnabled; } bool getAddNewSection() const { return this->addNewSection; } bool getReuseImports() const { return this->reuseImports; } protected: bool addNewSection; bool reuseImports; friend class StubMaker; }; class StubMaker { public: static bool makeStub(ExeHandler *exeHndl, const StubSettings &settings) { if (exeHndl == NULL) return false; bool isOk = false; PEFile *pe = dynamic_cast(exeHndl->getExe()); if (exeHndl->isHooked) { //File already hooked. Overwriting DataStore... isOk = overwriteDataStore(exeHndl); } else { isOk = makeStub(pe, exeHndl->m_FuncMap, exeHndl->m_Repl, settings); } if (isOk) { makeThunksWriteable(pe, &exeHndl->m_Repl); exeHndl->hasUnapplied = false; exeHndl->isModified = true; } exeHndl->rewrapFuncMap(); return isOk; } static size_t countMissingImports(ExeHandler *exeHndl) { return countMissingImports(exeHndl->m_FuncMap); } static bool fillHookedInfo(ExeHandler *exeHndl); protected: static Stub* makeStub(PEFile *pe); static bool setStubParams(Stub* stb, PEFile *pe, const offset_t newEntry, const offset_t dataRva, ImportsLookup &funcMap); static size_t calcReplNamesSize(FuncReplacements &funcRepl); static size_t calcDataStoreSize(FuncReplacements &funcRepl); static size_t calcNewImportsSize(PEFile *pe, size_t addedFuncCount); static ByteBuffer* makeDataStore(const offset_t dataRva, FuncReplacements &funcRepl); static bool readDataStore(AbstractByteBuffer* storeBuf, const offset_t dataRva, FuncReplacements &out_funcRepl); static bool overwriteDataStore(ExeHandler *exeHndl); // static ByteBuffer* createStub32(PEFile *peFile, offset_t stubRva, offset_t loadLib, offset_t getProcAddr); static size_t countMissingImports(ImportsLookup &funcMap); static bool makeThunksWriteable(PEFile *pe, FuncReplacements* m_funcRepl = NULL); static bool makeStub(PEFile *pe, ImportsLookup &funcMap, FuncReplacements &funcRepl, const StubSettings &settings); static bool addMissingFunctions(PEFile *pe, ImportsLookup &funcMap, bool tryReuse); static ImportEntryWrapper* addLibrary(PEFile *pe, QString name, offset_t &storageOffset); static bool addFunction(PEFile *pe, ImportEntryWrapper* libWr, ImportedFuncWrapper* func, const QString& name, offset_t &storageOffset); }; ================================================ FILE: patcher/application.qrc ================================================ icons/Add.ico icons/DeleteAll.ico icons/Delete.ico icons/reload.ico icons/app32.ico icons/app64.ico icons/apply.ico icons/save_black.ico icons/edit.ico icons/import.ico icons/export.ico favicon.ico ================================================ FILE: patcher/dllparse/FunctionsModel.cpp ================================================ #include "FunctionsModel.h" #include #include int FunctionsModel::countElements() const { if (m_LibInfos == NULL) return 0; LibraryInfo *info = m_LibInfos->at(m_libIndex); if (info == NULL) return 0; return info->getFunctionsCount(); } QVariant FunctionsModel::headerData(int section, Qt::Orientation orientation, int role) const { if (role != Qt::DisplayRole) return QVariant(); if (orientation != Qt::Horizontal) return QVariant(); switch (section) { case COL_NAME : return "Library Name"; } return QVariant(); } Qt::ItemFlags FunctionsModel::flags(const QModelIndex &index) const { if (!index.isValid()) return Qt::NoItemFlags; int elNum = index.row(); LibraryInfo *info = m_LibInfos->at(m_libIndex); if (info == NULL) return Qt::NoItemFlags; if (info->isFunctionNamed(elNum)) return Qt::ItemIsEnabled | Qt::ItemIsSelectable; return Qt::NoItemFlags; } bool FunctionsModel::setData(const QModelIndex &index, const QVariant &, int role) { return false; } QVariant FunctionsModel::data(const QModelIndex &index, int role) const { int elNum = index.row(); if (elNum > countElements()) return QVariant(); int attribute = index.column(); if (attribute >= COUNT_COL) return QVariant(); LibraryInfo *info = m_LibInfos->at(m_libIndex); if (info == NULL) return QVariant(); switch (role) { case Qt::DisplayRole: return info->getFuncNameAt(elNum); case Qt::UserRole : return elNum; case Qt::ToolTipRole: { if (!info->isFunctionNamed(elNum)) return "Not supported"; return ""; } } return QVariant(); } ================================================ FILE: patcher/dllparse/FunctionsModel.h ================================================ #pragma once #include #include #include "LibraryInfo.h" class FunctionsModel : public QAbstractTableModel { Q_OBJECT public slots: void modelChanged() { //> this->beginResetModel(); this->endResetModel(); //< } void on_currentndexChanged(int index) { //> this->beginResetModel(); m_libIndex = index; this->endResetModel(); //< } public: enum COLS { COL_NAME = 0, COUNT_COL }; FunctionsModel(QObject *v_parent) : QAbstractTableModel(v_parent), m_LibInfos(NULL) {} virtual ~FunctionsModel() { } QVariant headerData(int section, Qt::Orientation orientation, int role) const; Qt::ItemFlags flags(const QModelIndex &index) const; int columnCount(const QModelIndex &parent) const { return COUNT_COL; } int rowCount(const QModelIndex &parent) const { return countElements(); } QVariant data(const QModelIndex &index, int role) const; bool setData(const QModelIndex &, const QVariant &, int); QModelIndex index(int row, int column, const QModelIndex &parent = QModelIndex()) const { //no index item pointer return createIndex(row, column); } QModelIndex parent(const QModelIndex &index) const { return QModelIndex(); } // no parent public slots: void setLibraries(LibInfos* exes) { //> this->beginResetModel(); if (this->m_LibInfos != NULL) { //disconnect old QObject::disconnect(this->m_LibInfos, SIGNAL(listChanged()), this, SLOT( on_listChanged() ) ); } this->m_LibInfos = exes; if (this->m_LibInfos != NULL) { QObject::connect(this->m_LibInfos, SIGNAL(listChanged()), this, SLOT( on_listChanged() ) ); } this->endResetModel(); //< } protected slots: void on_listChanged() { //> this->beginResetModel(); this->endResetModel(); //< } protected: int countElements() const; LibInfos* m_LibInfos; size_t m_libIndex; }; ================================================ FILE: patcher/dllparse/LibraryInfo.cpp ================================================ #include "LibraryInfo.h" size_t LibInfos::size() { QMutexLocker lock(&m_listMutex); //LOCKER return m_Libs.size(); } LibraryInfo* LibInfos::at(size_t index) { QMutexLocker lock(&m_listMutex); //LOCKER if (index >= m_Libs.size()) return NULL; return m_Libs.at(index); } bool LibInfos::_addElement(LibraryInfo *hndl) { if (hndl == NULL) return false; { //start locked scope QMutexLocker lock(&m_listMutex); //LOCKER const QString fileName = hndl->getFileName(); if (m_NameToLibInfo.contains(fileName)) { //already exist, reload... LibraryInfo *info = m_NameToLibInfo[fileName]; m_Libs.removeOne(info); delete info; } m_Libs.push_back(hndl); m_NameToLibInfo[fileName] = hndl; } //end locked scope connect(hndl, SIGNAL(stateChanged()), this, SLOT(onChildStateChanged())); return true; } bool LibInfos::_removeElement(LibraryInfo *exe) { QMutexLocker lock(&m_listMutex); //LOCKER size_t indx = m_Libs.indexOf(exe); if (indx != -1) { m_Libs.removeAt(indx); return true; } return false; } QStringList LibInfos::listLibs() { QStringList fileNames; QList::iterator itr; QString fileName = ""; QMutexLocker lock(&m_listMutex); //LOCKER for (itr = m_Libs.begin(); itr != m_Libs.end(); itr++) { LibraryInfo *info = (*itr); fileNames << info->getLibName(); } return fileNames; } void LibInfos::_clear() { QMutexLocker lock(&m_listMutex); //LOCKER QList::iterator itr; for (itr = m_Libs.begin(); itr != m_Libs.end(); itr++) { LibraryInfo *exe = (*itr); delete exe; } m_Libs.clear(); } ================================================ FILE: patcher/dllparse/LibraryInfo.h ================================================ #pragma once #include #include class FunctionInfo { public: FunctionInfo(QString v_name, bool v_isByOrdinal=false) : name(v_name), isByOrdinal(v_isByOrdinal) {} virtual ~FunctionInfo() {} protected: QString name; bool isByOrdinal; friend class LibraryInfo; }; class LibraryInfo : public QObject { Q_OBJECT signals: void stateChanged(); public: LibraryInfo(QString filename, QObject* parent = NULL) : QObject(parent), fileName(filename) { QFileInfo inputInfo(filename); libName = inputInfo.fileName(); } ~LibraryInfo() {} QString getFileName() { return fileName; } QString getLibName() { return libName; } const QString getFuncNameAt(int i) { if (i > functions.size()) return ""; return functions.at(i).name; } bool isFunctionNamed(int i) const { if (i > functions.size()) return false; return !(functions.at(i).isByOrdinal); } size_t getFunctionsCount() const { return functions.size(); } protected: QString libName; QString fileName; QList functions; friend class LibraryParser; }; class LibInfos : public QObject { Q_OBJECT signals: void listChanged(); public slots: void addElement(LibraryInfo *info) { if (_addElement(info)) emit listChanged(); } void removeElement(LibraryInfo *info) { if (_removeElement(info)) emit listChanged(); } void clear() { _clear(); emit listChanged(); } public: size_t size(); LibraryInfo* at(size_t index); QStringList listLibs(); protected slots: void onChildStateChanged() { emit listChanged(); } private: bool _addElement(LibraryInfo *info); bool _removeElement(LibraryInfo *info); void _clear(); QList m_Libs; QMap m_NameToLibInfo; QMutex m_listMutex; }; ================================================ FILE: patcher/dllparse/LibraryParser.cpp ================================================ #include "LibraryParser.h" void LibraryParser::on_parseLibrary(QString& fileName) { try { FileView *buf = new FileView(fileName); ExeFactory::exe_type exeType = ExeFactory::findMatching(buf); if (exeType == ExeFactory::NONE) { delete buf; return; } Executable *exe = ExeFactory::build(buf, exeType); makeLibraryInfo(exe, fileName); delete exe; delete buf; } catch (CustomException &e) { printf("ERR: %s\n", e.what()); } } ExportDirWrapper* LibraryParser::getExports(Executable* exe) { MappedExe *mappedExe = dynamic_cast(exe); if (mappedExe == NULL) return NULL; return dynamic_cast(mappedExe->getWrapper(PEFile::WR_DIR_ENTRY + pe::DIR_EXPORT)); } void LibraryParser::makeLibraryInfo(Executable* exe, QString fileName) { if (!exe) return; ExportDirWrapper* exports = getExports(exe); if (!exports) return; size_t entriesCnt = exports->getEntriesCount(); if (entriesCnt == 0) return; LibraryInfo *info = new LibraryInfo(fileName); for(int i = 0; i < entriesCnt; i++) { ExportEntryWrapper* entry = dynamic_cast(exports->getEntryAt(i)); if (!entry) continue; info->functions.append(FunctionInfo(entry->getName(), entry->isByOrdinal())); } emit infoCreated(info); } ================================================ FILE: patcher/dllparse/LibraryParser.h ================================================ #pragma once #include #include #include "LibraryInfo.h" class LibraryParser: public QObject { Q_OBJECT signals: void infoCreated(LibraryInfo*); public: LibraryParser(QObject* parent = NULL) : QObject(parent) {} ~LibraryParser(){} void makeLibraryInfo(Executable* exe, QString fileName); ExportDirWrapper* getExports(Executable* exe); public slots: void on_parseLibrary(QString&); }; ================================================ FILE: patcher/dllparse/LibsModel.cpp ================================================ #include "LibsModel.h" #include #include #include QVariant LibsModel::headerData(int section, Qt::Orientation orientation, int role) const { if (role != Qt::DisplayRole) return QVariant(); if (orientation != Qt::Horizontal) return QVariant(); switch (section) { case COL_NAME : return "Library Name"; } return QVariant(); } Qt::ItemFlags LibsModel::flags(const QModelIndex &index) const { if (!index.isValid()) return 0; Qt::ItemFlags f = Qt::ItemIsEnabled | Qt::ItemIsSelectable; return f; } bool LibsModel::setData(const QModelIndex &index, const QVariant &, int role) { return false; } QVariant LibsModel::data(const QModelIndex &index, int role) const { int elNum = index.row(); if (elNum > countElements()) return QVariant(); int attribute = index.column(); if (attribute >= COUNT_COL) return QVariant(); LibraryInfo *info = m_LibInfos->at(elNum); if (info == NULL) return QVariant(); switch (role) { case Qt::DisplayRole: return info->getLibName(); case Qt::ToolTipRole: return info->getFileName(); case Qt::UserRole : return elNum; } return QVariant(); } ================================================ FILE: patcher/dllparse/LibsModel.h ================================================ #pragma once #include #include #include "LibraryInfo.h" class LibsModel : public QAbstractTableModel { Q_OBJECT public slots: void modelChanged() { //> this->beginResetModel(); this->endResetModel(); //< } public: enum COLS { COL_NAME = 0, COUNT_COL }; LibsModel(QObject *v_parent) : QAbstractTableModel(v_parent), m_LibInfos(NULL) {} virtual ~LibsModel() { } QVariant headerData(int section, Qt::Orientation orientation, int role) const; Qt::ItemFlags flags(const QModelIndex &index) const; int columnCount(const QModelIndex &parent) const { return COUNT_COL; } int rowCount(const QModelIndex &parent) const { return countElements(); } QVariant data(const QModelIndex &index, int role) const; bool setData(const QModelIndex &, const QVariant &, int); QModelIndex index(int row, int column, const QModelIndex &parent = QModelIndex()) const { //no index item pointer return createIndex(row, column); } QModelIndex parent(const QModelIndex &index) const { return QModelIndex(); } // no parent public slots: void setLibraries(LibInfos* exes) { //> this->beginResetModel(); if (this->m_LibInfos != NULL) { //disconnect old QObject::disconnect(this->m_LibInfos, SIGNAL(listChanged()), this, SLOT( on_listChanged() ) ); } this->m_LibInfos = exes; if (this->m_LibInfos != NULL) { QObject::connect(this->m_LibInfos, SIGNAL(listChanged()), this, SLOT( on_listChanged() ) ); } this->endResetModel(); //< } protected slots: void on_listChanged() { //> this->beginResetModel(); this->endResetModel(); //< } protected: LibInfos* m_LibInfos; int countElements() const { return (m_LibInfos == NULL)? 0: m_LibInfos->size(); } }; ================================================ FILE: patcher/main.cpp ================================================ #include "mainwindow.h" #include #include #include #include int main(int argc, char *argv[]) { Q_INIT_RESOURCE(application); QApplication app(argc, argv); ExeFactory::init(); MainWindow w; w.show(); return app.exec(); } ================================================ FILE: patcher/mainwindow.cpp ================================================ #include "mainwindow.h" #include #include #include #include "ExeHandlerLoader.h" #include "ImportsTableModel.h" #include "StubMaker.h" MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), m_replacementsDialog(NULL), exeController(this), infoModel(NULL), m_libsModel(NULL), m_functModel(NULL), m_ExeSelected(NULL), customMenu(NULL), functionsMenu(NULL) { m_ui.setupUi(this); initReplacementsDialog(); makeCustomMenu(); makeFunctionsMenu(); makeFileMenu(); this->setWindowTitle("IAT Patcher v " + QString(VERSION) + " Qt" + QString::number(QT_VER_NUM, 10)); this->infoModel = new InfoTableModel(m_ui.outputTable); infoModel->setExecutables(&m_exes); m_ui.outputTable->setModel(infoModel); m_ui.outputTable->setSortingEnabled(false); m_ui.outputTable->horizontalHeader()->setSectionResizeMode(QHeaderView::Interactive); m_ui.outputTable->horizontalHeader()->setSectionResizeMode(0, QHeaderView::Stretch); m_ui.outputTable->verticalHeader()->show(); m_ui.outputTable->setSelectionBehavior(QAbstractItemView::SelectRows); m_ui.outputTable->setSelectionMode(QAbstractItemView::SingleSelection); m_ui.outputTable->setEditTriggers(QAbstractItemView::NoEditTriggers); m_ui.statusBar->addPermanentWidget(&urlLabel); urlLabel.setTextFormat(Qt::RichText); urlLabel.setTextInteractionFlags(Qt::TextBrowserInteraction); urlLabel.setOpenExternalLinks(true); urlLabel.setText(""+SITE_LINK+""); this->setAcceptDrops(true); this->impModel = new ImportsTableModel(m_ui.outputTable); this->m_filteredImpModel = new QSortFilterProxyModel(this); m_filteredImpModel->setDynamicSortFilter(true); m_filteredImpModel->setSourceModel(impModel); m_ui.importsTable->setModel(m_filteredImpModel); m_ui.importsTable->setSortingEnabled(true); m_ui.importsTable->setSelectionBehavior(QAbstractItemView::SelectRows); m_ui.importsTable->setSelectionMode(QAbstractItemView::SingleSelection); m_ui.importsTable->horizontalHeader()->setSectionResizeMode(2, QHeaderView::Stretch); connect( m_ui.filterLibEdit, SIGNAL( textChanged (const QString &)), this, SLOT( filterLibs(const QString &)) ); connect( m_ui.filterProcEdit, SIGNAL( textChanged (const QString &)), this, SLOT( filterFuncs(const QString &)) ); m_ui.outputTable->setContextMenuPolicy(Qt::CustomContextMenu); connect(m_ui.outputTable, SIGNAL(customContextMenuRequested(QPoint)), SLOT(customMenuRequested(QPoint))); m_ui.importsTable->setContextMenuPolicy(Qt::CustomContextMenu); connect(m_ui.importsTable, SIGNAL(customContextMenuRequested(QPoint)), SLOT(functionsMenuRequested(QPoint))); connect( m_ui.outputTable->selectionModel(), SIGNAL( currentRowChanged(QModelIndex,QModelIndex)), this, SLOT( rowChangedSlot(QModelIndex,QModelIndex) ) ); connect( this, SIGNAL( exeSelected(ExeHandler*)), impModel, SLOT( setExecutable(ExeHandler*) ) ); connect( this, SIGNAL( exeSelected(ExeHandler*)), this, SLOT( refreshExeView(ExeHandler*) ) ); connect( this, SIGNAL( exeUpdated(ExeHandler*)), impModel, SLOT( setExecutable(ExeHandler*) ) ); connect( this, SIGNAL( exeUpdated(ExeHandler*)), infoModel, SLOT( onExeListChanged() ) ); connect( &this->exeController, SIGNAL( exeUpdated(ExeHandler*)), this, SLOT( refreshExeView(ExeHandler*)) ); connect( &this->exeController, SIGNAL(exeUpdated(ExeHandler*)), infoModel, SLOT(onExeListChanged()) ); connect(&m_LoadersCount, SIGNAL(counterChanged()), this, SLOT(loadingStatusChanged() )); connect(this, SIGNAL(hookRequested(ExeHandler* )), this, SLOT(onHookRequested(ExeHandler* ) )); connect(infoModel, SIGNAL(hookRequested(ExeHandler* )), this, SLOT(onHookRequested(ExeHandler* )) ); connect(this, SIGNAL(thunkSelected(offset_t)), this, SLOT(setThunkSelected(offset_t)) ); } MainWindow::~MainWindow() { clear(); } void MainWindow::initReplacementsDialog() { m_replacementsDialog = new ReplacementsDialog(this); connect(m_replacementsDialog, SIGNAL(setReplacement(QString, QString)), this, SLOT(updateReplacement(QString, QString)) ); connect(this, SIGNAL(replacementAccepted()), m_replacementsDialog, SLOT(hide())); } void MainWindow::filterLibs(const QString &str) { m_filteredImpModel->setFilterRegExp(QRegExp(str, Qt::CaseInsensitive, QRegExp::FixedString)); m_filteredImpModel->setFilterKeyColumn(1); } void MainWindow::filterFuncs(const QString &str) { m_filteredImpModel->setFilterRegExp(QRegExp(str, Qt::CaseInsensitive, QRegExp::FixedString)); m_filteredImpModel->setFilterKeyColumn(2); } void MainWindow::refreshExeView(ExeHandler* exe) { if (m_ExeSelected == exe) { QString fName = ""; if (exe) fName = exe->getFileName(); this->m_ui.fileEdit->setText(fName); } } void MainWindow::loadingStatusChanged() { size_t count = m_LoadersCount.getCount(); if (count == 0) { this->m_ui.statusBar->showMessage(""); return; } QString ending = "s"; if (count == 1) ending = ""; this->m_ui.statusBar->showMessage("Loading: " + QString::number(count) + " file" + ending); } void MainWindow::dropEvent(QDropEvent* ev) { QList urls = ev->mimeData()->urls(); QList::Iterator urlItr; QCursor cur = this->cursor(); this->setCursor(Qt::BusyCursor); for (urlItr = urls.begin() ; urlItr != urls.end(); urlItr++) { QString fileName = urlItr->toLocalFile(); if (fileName == "") continue; if (parse(fileName)) { m_ui.fileEdit->setText(fileName); } } this->setCursor(cur); } void MainWindow::closeEvent ( QCloseEvent * event ) { const size_t loadedCount = this->m_exes.size(); if (loadedCount == 0) { event->accept(); return; } event->ignore(); bool hasModified = false; for (int i = 0; i < loadedCount; i++) { ExeHandler *hndl = this->m_exes.at(i); if (hndl->getModifiedState() || hndl->getUnappliedState()) { hasModified = true; break; } } if (!hasModified) { event->accept(); return; } if (QMessageBox::Yes == QMessageBox::question(this, "Exit confirmation", "You made some unsaved changes, do you really want to exit?", QMessageBox::Yes|QMessageBox::No)) { event->accept(); } } void MainWindow::on_pushButton_clicked() { return openExe(); } void MainWindow::openExe() { QString fileName = QFileDialog::getOpenFileName( this, tr("Open executable"), QDir::homePath(), "Exe Files (*.exe);;DLL Files (*.dll);;All files (*)" ); if (fileName != "") { this->parse(fileName); } } void MainWindow::removeExe(ExeHandler* exe) { selectExe(NULL); this->m_exes.removeExe(exe); delete exe; exe = NULL; } void MainWindow::on_reloadButton_clicked() { QStringList files = this->m_exes.listFiles(); clear(); QStringList::iterator itr; for (itr = files.begin(); itr != files.end(); itr++) { QString fileName = *itr; this->parse(fileName); } } void MainWindow::reloadExe(ExeHandler* exe) { QString fName = ""; if (exe && exe->getExe()) fName = exe->getFileName(); this->removeExe(exe); this->parse(fName); } void MainWindow::saveRequested(ExeHandler* exeHndl) { if (exeHndl == NULL) { QMessageBox::warning(this, "Cannot save!", "No executable selected!"); return; } Executable *exe = exeHndl->getExe(); if (exe == NULL) return; if (exeHndl->getUnappliedState()) { QMessageBox::warning(this, "Unapplied replacements!", "The file has unapplied replacements. Hook the file to apply them."); return; } if (exeHndl->getHookedState() == false) { QMessageBox::StandardButton reply; reply = QMessageBox::question(this, "Unhooked file!", "You are trying to save unhooked file. Do you really want?", QMessageBox::Yes | QMessageBox::No ); if (reply == QMessageBox::No) { return; } } QFileInfo inputInfo(exeHndl->getFileName()); QString infoStr = "Save executable as:"; QString fileName = QFileDialog::getSaveFileName( this, infoStr, inputInfo.absoluteDir().path(), "Exe Files (*.exe);;DLL Files (*.dll);;All files (*)" ); if (fileName.length() == 0) return; try { this->exeController.saveExecutable(exeHndl, fileName); } catch (CustomException &e) { QMessageBox::warning(this, "Error!", e.getInfo()); } } void MainWindow::hookExecutable(ExeHandler* exeHndl, StubSettings &settings) { if (exeHndl == NULL) return; Executable *exe = exeHndl->getExe(); if (exe == NULL) return; bool isHooked = exeHndl->getHookedState(); PEFile *pe = dynamic_cast(exe); if (pe == NULL) { QMessageBox::warning(this, "Cannot hook!", "It is not a PE File!"); return; } if (isHooked) { if (exeHndl->getUnappliedState() == false) { QMessageBox::information(NULL, "No changes!", "No changes to be applied"); return; } QMessageBox::StandardButton reply; reply = QMessageBox::question(this, "Already hooked!", "This file is already hooked.\nDo you want to modify the existing stub?", QMessageBox::Yes | QMessageBox::No ); if (reply == QMessageBox::No) { return; } } if (exeHndl->hasReplacements() == false && exeHndl->getHookedState() == false) { QMessageBox::StandardButton reply; reply = QMessageBox::question(this, "No replacements!", "You haven't defined any replacement functions.\nDo you really want to add an empty stub?", QMessageBox::Yes | QMessageBox::No ); if (reply == QMessageBox::No) { return; } } if (!isHooked && pe->canAddNewSection() == false && settings.getAddNewSection()) { QMessageBox::information(this, "Warning", "Cannot add new section in this file!\nProceed by extending last section..."); } try { if (this->exeController.hookExecutable(exeHndl, settings)) { QMessageBox::information(this, "Done!", "Hooked!\nNow you can save and test the file!"); return; } else { QMessageBox::warning(this, "Failed", "Cannot hook!"); } } catch (CustomException &e) { QMessageBox::warning(this, "Error!", e.getInfo()); } } void MainWindow::clear() { selectExe(NULL); this->m_exes.clear(); } void MainWindow::on_hookButton_clicked() { emit hookRequested(this->m_ExeSelected); } QAction* MainWindow::addExeAction(QMenu *customMenu, QString text, ExeController::EXE_ACTION a) { QAction *action = new QAction(text, customMenu); action->setData(a); customMenu->addAction(action); connect(action, SIGNAL(triggered()), this, SLOT(takeAction())); return action; } void MainWindow::makeCustomMenu() { this->customMenu = new QMenu(this); addExeAction(customMenu, "Hook", ExeController::ACTION_HOOK)->setIcon(QIcon(":/icons/apply.ico")); addExeAction(customMenu, "Save as...", ExeController::ACTION_SAVE)->setIcon(QIcon(":/icons/save_black.ico")); addExeAction(customMenu, "Reload", ExeController::ACTION_RELOAD)->setIcon(QIcon(":/icons/reload.ico")); addExeAction(customMenu, "Unload", ExeController::ACTION_UNLOAD)->setIcon(QIcon(":icons/Delete.ico")); customMenu->addSeparator(); addExeAction(customMenu, "Export replacements", ExeController::ACTION_EXPORT_REPL)->setIcon(QIcon(":icons/export.ico")); addExeAction(customMenu, "Import replacements", ExeController::ACTION_IMPORT_REPL)->setIcon(QIcon(":icons/import.ico")); } void MainWindow::makeFunctionsMenu() { this->functionsMenu = new QMenu(this); QAction *settingsAction = new QAction("Define replacement", functionsMenu); settingsAction->setIcon(QIcon(":icons/edit.ico")); connect(settingsAction, SIGNAL(triggered()), this->m_replacementsDialog, SLOT(show())); functionsMenu->addAction(settingsAction); } void MainWindow::makeFileMenu() { QMenu *menu = this->m_ui.menuFile; QAction *openAction = new QAction("Open executable", menu); openAction->setIcon(QIcon(":/icons/Add.ico")); connect(openAction, SIGNAL(triggered()), this, SLOT(openExe())); menu->addAction(openAction); addExeAction(menu, "Hook selected", ExeController::ACTION_HOOK)->setIcon(QIcon(":/icons/apply.ico")); addExeAction(menu, "Save selected as...", ExeController::ACTION_SAVE)->setIcon(QIcon(":/icons/save_black.ico")); } void MainWindow::customMenuRequested(QPoint pos) { QTableView *table = this->m_ui.outputTable; QModelIndex index = table->indexAt(pos); if (index.isValid() == false) return; this->customMenu->popup(table->viewport()->mapToGlobal(pos)); } void MainWindow::functionsMenuRequested(QPoint pos) { QTableView *table = this->m_ui.importsTable; if (table == NULL ) return; if (this->m_ExeSelected == NULL) return; QModelIndex index = table->indexAt(pos); if (index.isValid() == false) return; bool isOk; long long offset = m_filteredImpModel->data(index, Qt::UserRole).toLongLong(&isOk); m_ThunkSelected = isOk ? offset : INVALID_ADDR; emit thunkSelected(m_ThunkSelected); FuncDesc replName = this->m_ExeSelected->getReplAt(m_ThunkSelected); this->m_replacementsDialog->displayReplacement(replName); this->functionsMenu->popup(table->viewport()->mapToGlobal(pos)); } void MainWindow::setThunkSelected(offset_t thunk) { QString libName = this->m_ExeSelected->m_FuncMap.thunkToLibName(thunk); QString funcName = this->m_ExeSelected->m_FuncMap.thunkToFuncName(thunk); this->m_replacementsDialog->displayFuncToReplace(thunk, libName, funcName); } void MainWindow::updateReplacement(QString libName, QString funcName) { QString substName = ""; if (libName.length() != 0 && funcName.length() != 0) { substName = libName + "." + funcName; } if (this->m_ExeSelected->m_Repl.getAt(m_ThunkSelected) == substName) { emit replacementAccepted(); return; } if (this->m_ExeSelected->defineReplacement(m_ThunkSelected, substName) == false) { QMessageBox::warning(this, "Error", "Invalid replacement definition!"); return; } emit replacementAccepted(); } void MainWindow::onImportReplacements(ExeHandler* exeHndl) { if (exeHndl == NULL) return; QString infoStr = "Import replacements"; QFileInfo inputInfo(exeHndl->getFileName()); QString fileName = QFileDialog::getOpenFileName( this, infoStr, inputInfo.absoluteDir().path(), "Config file (*.txt);;Config file (*.cfg);;All files (*)" ); if (fileName.length() == 0) return; size_t counter = this->exeController.loadReplacementsFromFile(exeHndl, fileName); if (counter == 0) { QMessageBox::warning(NULL, "Error!", "Cannot import!"); return; } if (counter > 0) { QString ending = (counter > 1) ? "s" : " "; QMessageBox::information(NULL, "Done!", "Imported: " + QString::number(counter) + " replacement" + ending); } } void MainWindow::onExportReplacements(ExeHandler* exeHndl) { if (exeHndl == NULL) return; if (exeHndl->hasReplacements() == false) { QMessageBox::warning(NULL, "Cannot save!", "The file have NO replacements defined!"); return; } QString infoStr = "Save replacements as..."; QFileInfo inputInfo(exeHndl->getFileName()); QString fileName = QFileDialog::getSaveFileName( this, infoStr, inputInfo.absoluteDir().path(), "Config file (*.txt);;Config file (*.cfg);;All files (*)" ); if (fileName.length() == 0) return; size_t counter = this->exeController.saveReplacementsToFile(exeHndl, fileName); if (counter == 0) { QMessageBox::warning(NULL, "Error!", "Cannot export!"); } else { QString ending = (counter > 1) ? "s" : " "; QMessageBox::information(NULL, "Done!", "Exported: " + QString::number(counter) + " replacement" + ending); } } void MainWindow::takeAction() { QAction *action = qobject_cast(sender()); //TODO : refactor it if (action->data() == ExeController::ACTION_HOOK) { emit hookRequested(this->m_ExeSelected); return; } if (action->data() == ExeController::ACTION_SAVE) { this->saveRequested(this->m_ExeSelected); return; } if (action->data() == ExeController::ACTION_UNLOAD) { this->removeExe(this->m_ExeSelected); return; } if (action->data() == ExeController::ACTION_RELOAD) { this->reloadExe(this->m_ExeSelected); return; } if (action->data() == ExeController::ACTION_IMPORT_REPL) { this->onImportReplacements(this->m_ExeSelected); return; } if (action->data() == ExeController::ACTION_EXPORT_REPL) { this->onExportReplacements(this->m_ExeSelected); return; } } void MainWindow::onHookRequested(ExeHandler* exeHndl) { StubSettings settings; settings.setAddNewSection(this->m_ui.actionAdd_new_section->isChecked()); settings.setReuseImports(this->m_ui.actionAdd_imports->isChecked()); QString settingsStr = "Settings: "; if (settings.getAddNewSection()) { settingsStr += "add new section ;"; } if (settings.getReuseImports()) { settingsStr += "reuse imports"; } this->m_ui.statusBar->showMessage(settingsStr); this->hookExecutable(exeHndl, settings); } void MainWindow::on_saveButton_clicked() { saveRequested(this->m_ExeSelected); } void MainWindow::onLoadingFailed(QString fileName) { QMessageBox::warning(this, "Error!", "Cannot load the file: " + fileName); } void MainWindow::onLoaderThreadFinished() { delete QObject::sender(); m_LoadersCount.dec(); this->repaint(); } void MainWindow::rowChangedSlot(QModelIndex curr, QModelIndex prev) { bool isOk = false; size_t index = this->infoModel->data(curr, Qt::UserRole).toUInt(&isOk); if (!isOk) return; ExeHandler *exe = this->m_exes.at(index); selectExe(exe); } bool MainWindow::parse(QString &fileName) { if (fileName == "") return false; QString link = QFile::symLinkTarget(fileName); if (link.length() > 0) fileName = link; bufsize_t maxMapSize = FILE_MAXSIZE; try { FileView fileView(fileName, maxMapSize); ExeFactory::exe_type exeType = ExeFactory::findMatching(&fileView); if (exeType == ExeFactory::NONE) { QMessageBox::warning(this, "Cannot parse!", "Cannot parse the file: \n"+fileName+"\n\nType not supported."); return false; } ExeHandlerLoader *loader = new ExeHandlerLoader(fileName); QObject::connect(loader, SIGNAL( loaded(ExeHandler*) ), &m_exes, SLOT( addExe(ExeHandler*) ) ); QObject::connect(loader, SIGNAL( loadingFailed(QString ) ), this, SLOT( onLoadingFailed(QString ) ) ); QObject::connect(loader, SIGNAL(finished()), this, SLOT( onLoaderThreadFinished() ) ); //printf("Thread started...\n"); m_LoadersCount.inc(); loader->start(); } catch (CustomException &e) { QMessageBox::warning(this, "ERROR", e.getInfo()); return false; } return true; } void MainWindow::info() { int ret = 0; int count = 0; QPixmap p(":/favicon.ico"); QString msg = "IAT Patcher - tool for persistent IAT hooking
"; msg += "author: hasherezade
"; msg += "using: Qt" + QString::number(QT_VER_NUM, 10) + "

"; msg += "LICENSE: " + LICENSE_TYPE + "
"; msg += "Sourcecode & more info
"; msg += "Report an issue"; QMessageBox *msgBox = new QMessageBox(this); msgBox->setAttribute(Qt::WA_DeleteOnClose); msgBox->setWindowTitle("Info"); msgBox->setTextFormat(Qt::RichText); msgBox->setText(msg); msgBox->setAutoFillBackground(true); msgBox->setIconPixmap(p); msgBox->setStandardButtons(QMessageBox::Ok); msgBox->exec(); } ================================================ FILE: patcher/mainwindow.h ================================================ #pragma once #include #include #include "Executables.h" #include "ui_mainwindow.h" #include "ui_replacements.h" #include "ImportsTableModel.h" #include "InfoTableModel.h" #include "ExeController.h" #include "ReplacementsDialog.h" #ifndef QT_VERSION_MAJOR #define QT_VER_NUM 5 #else #define QT_VER_NUM QT_VERSION_MAJOR #endif #define VERSION "0.3.5.4" #define MY_SITE_LINK "https://hasherezade.net/" #define LICENSE_TYPE "BSD-2" #define LICENSE_LINK "https://raw.githubusercontent.com/hasherezade/IAT_patcher/master/LICENSE" #define SITE_LINK "http://hasherezade.github.io/IAT_patcher/" #define ISSUES_LINK "https://github.com/hasherezade/IAT_patcher/issues" class ThreadCounter : public QObject { Q_OBJECT signals: void counterChanged(); public: ThreadCounter() { counter = 0; } void inc() { { QMutexLocker lock(&m_Mutex); counter++; } emit counterChanged(); } void dec() { { QMutexLocker lock(&m_Mutex); counter--; } emit counterChanged(); } size_t getCount() { QMutexLocker lock(&m_Mutex); return counter; } protected: size_t counter; QMutex m_Mutex; }; class MainWindow : public QMainWindow { Q_OBJECT signals: void exeSelected(ExeHandler* exe); void exeUpdated(ExeHandler* exe); void hookRequested(ExeHandler* exe); void thunkSelected(offset_t thunk); void replacementAccepted(); public: explicit MainWindow(QWidget *parent = 0); ~MainWindow(); protected: /* events */ void dragEnterEvent(QDragEnterEvent* ev) { ev->accept(); } void dropEvent(QDropEvent* ev); void closeEvent(QCloseEvent* ev); private slots: void filterLibs(const QString &str); void filterFuncs(const QString &str); void takeAction(); void loadingStatusChanged(); void onLoadingFailed(QString fileName); void selectExe(ExeHandler* exe) { m_ExeSelected = exe; emit exeSelected(exe); } void refreshExeView(ExeHandler* exe); void customMenuRequested(QPoint pos); void functionsMenuRequested(QPoint pos); void onHookRequested(ExeHandler* exeHndl); void updateReplacement(QString libName, QString funcName); void onExportReplacements(ExeHandler* exeHndl); void onImportReplacements(ExeHandler* exeHndl); void setThunkSelected(offset_t thunk); void onLoaderThreadFinished(); void rowChangedSlot(QModelIndex, QModelIndex); void openExe(); //--- void on_pushButton_clicked(); void on_reloadButton_clicked(); void on_clearAllButton_clicked() { clear(); } void on_hookButton_clicked(); void on_saveButton_clicked(); void on_actionAbout_triggered() { info(); } private: void reloadExe(ExeHandler* exe); void removeExe(ExeHandler* exe); void saveRequested(ExeHandler* exeHndl); void hookExecutable(ExeHandler* exeHndl, StubSettings &settings); void info(); void clear(); bool parse(QString &fileName); QAction* addExeAction(QMenu *customMenu, QString text, ExeController::EXE_ACTION a); void makeCustomMenu(); void makeFunctionsMenu(); void makeFileMenu(); void initReplacementsDialog(); ReplacementsDialog *m_replacementsDialog; QMenu *customMenu, *functionsMenu; QSortFilterProxyModel *m_filteredImpModel; Ui::MainWindow m_ui; ImportsTableModel *impModel; InfoTableModel *infoModel; LibsModel *m_libsModel; FunctionsModel *m_functModel; ThreadCounter m_LoadersCount; Executables m_exes; ExeHandler* m_ExeSelected; offset_t m_ThunkSelected; QLabel urlLabel; ExeController exeController; }; ================================================ FILE: patcher/mainwindow.ui ================================================ hasherezade MainWindow Qt::ApplicationModal 0 0 731 522 100 300 Qt::StrongFocus IAT Patcher :/favicon.ico:/favicon.ico 1.000000000000000 Qt::LeftToRight true QTabWidget::Rounded QLayout::SetMinAndMaxSize true Selected executable 0 0 Open file :/icons/Add.ico:/icons/Add.ico 24 24 true false 0 0 Reload all :/icons/reload.ico:/icons/reload.ico 24 24 true false 0 0 Unload all :/icons/DeleteAll.ico:/icons/DeleteAll.ico 24 24 true false Preview: Qt::Vertical true 0 0 true QFrame::StyledPanel true true true 0 0 0 40 16777215 38 1 1 0 0 false false Filter libraries 0 0 false false Filter functions 0 0 Qt::LeftToRight true true true Hook! :/icons/apply.ico:/icons/apply.ico Save :/icons/save_black.ico:/icons/save_black.ico 0 0 731 21 Info Settings File About true true Add new section true true Reuse imports Open PE Save PE as.. - Open hooking schema Save hooking schema 10 10 true true true ================================================ FILE: patcher/replacements.ui ================================================ Replacements Qt::WindowModal 0 0 410 337 0 0 410 320 410 500 Qt::CustomContextMenu true Define replacement true false false 10 300 381 32 Qt::Horizontal QDialogButtonBox::Cancel|QDialogButtonBox::Ok 10 10 391 101 0 0 Replace: false false 9 5 9 5 10 5 true Thunk: Function: true true 10 110 391 191 0 0 With: false false 5 20 5 5 10 5 0 0 Qt::DefaultContextMenu 0 Edit 0 0 361 91 QLayout::SetDefaultConstraint 10 10 10 0 example.dll Function: functionName Library: Choose 0 0 361 91 10 10 10 30 16777215 <html><head/><body><p>Load replacement library</p></body></html> true + 50 0 Function: 50 16777215 Library: okCancel_buttons thunkLabel libToReplaceLabel ================================================ FILE: patcher/stub/Stub.cpp ================================================ #include "Stub.h" bool StubParam::insertIntoBuffer(AbstractByteBuffer* buf) { if (buf == NULL) return false; offset_t fullOffset = this->m_bigOffset + this->m_smallOffset; bool isOk = buf->setNumValue(fullOffset, this->m_valueSize, this->m_value); //TODO - verify if setting succeseded? return true; } bool StubParam::readFromBuffer(AbstractByteBuffer* buf) { if (buf == NULL) return false; offset_t fullOffset = this->m_bigOffset + this->m_smallOffset; bool isOk = false; offset_t value = buf->getNumValue(fullOffset, this->m_valueSize, &isOk); if (!isOk) return false; this->m_value = value; return true; } //----- ByteBuffer* Stub::createStubBuffer() { ByteBuffer* buf = bufferStubData(); if (buf == NULL) return NULL; if (this->fillParams(buf) == false) { printf("Unable to fill params!\n"); delete buf; return NULL; } return buf; } ByteBuffer* Stub::bufferStubData() { const unsigned char* originalData = this->getData(); const bufsize_t stubSize = this->getSize(); unsigned char *stubData = new unsigned char[stubSize]; memcpy(stubData, originalData, stubSize); ByteBuffer *stubBuf = new ByteBuffer(stubData, stubSize, 0); delete []stubData; return stubBuf; } bool Stub::fillParam(size_t id, AbstractByteBuffer* buf) { StubParam *param = this->getParam(id); if (param == NULL) { //Param not found return false; } if (param->m_relativeToId != param->m_id) { offset_t dif = this->paramDistance(param->m_relativeToId, id); param->setValue(dif); } return param->insertIntoBuffer(buf); } bool Stub::fillParams(AbstractByteBuffer* buf) { std::map::iterator itr; for (itr = m_params.begin(); itr != m_params.end(); itr++) { size_t paramId = itr->first; if (fillParam(paramId, buf) == false) { return false; } } return true; } offset_t Stub::getAbsoluteValue(StubParam *param) { if (param == NULL) { return INVALID_ADDR; } offset_t myValue = param->m_value; if (param->m_relativeToId != param->m_id) { StubParam *relParam = this->getParam(param->m_relativeToId); if (relParam == NULL) return INVALID_ADDR; offset_t dif = ((int32_t) param->m_value); offset_t relValue = relParam->m_value; myValue = relParam->m_value + dif + param->getTotalOffset() + param->getValueSize(); } return myValue; } bool Stub::readParam(size_t id, AbstractByteBuffer* buf) { StubParam *param = this->getParam(id); if (param == NULL) { //Param not found return false; } if (param->readFromBuffer(buf) == false) return false; offset_t myValue = getAbsoluteValue(param); if (myValue == INVALID_ADDR) return false; param->setValue(myValue); return true; } bool Stub::readParams(AbstractByteBuffer* buf) { std::map::iterator itr; for (itr = m_params.begin(); itr != m_params.end(); itr++) { size_t paramId = itr->first; if (!readParam(paramId, buf)) { return false; } } return true; } void Stub::deleteParams() { bool isOk = false; std::map::iterator itr; for (itr = m_params.begin(); itr != m_params.end(); itr++) { StubParam* param = itr->second; delete param; } m_params.clear(); } bool Stub::containsStub(AbstractByteBuffer *buf) const { const unsigned char* stubData = this->getData(); const bufsize_t stubSize = this->getSize(); const offset_t signStart = getSignatureStart(); const offset_t signEnd = getSignatureEnd(); /* sanity check */ if (buf == NULL) return false; if (buf->getContentSize() < stubSize) return false; unsigned char* bufData = (unsigned char*) buf->getContent(); if (bufData == NULL) return false; /* sanity check */ if (stubData == NULL || signStart > signEnd || signEnd >= stubSize) { printf("Malformated stub!"); return false; } bufData += signStart; const unsigned char* cmpData = stubData + signStart; const size_t cmpSize = signEnd - signStart; int res = memcmp(cmpData, bufData, cmpSize); if (res == 0) { return true; } return false; } ================================================ FILE: patcher/stub/Stub.h ================================================ #pragma once #include #include "../Executables.h" #include "../FuncReplacements.h" class StubParam { public: StubParam(size_t id, offset_t bigOffset, offset_t smallOffset, size_t valueSize, size_t relId) : m_id(id), m_bigOffset(bigOffset), m_smallOffset(smallOffset), m_valueSize(valueSize), m_value(0), m_relativeToId(relId) {} StubParam(size_t id, offset_t bigOffset, offset_t smallOffset, size_t valueSize) : m_id(id), m_bigOffset(bigOffset), m_smallOffset(smallOffset), m_valueSize(valueSize), m_value(0), m_relativeToId(id) {} virtual ~StubParam() { /*printf("Deleting param id = %d\n", m_id);*/ } void setValue(offset_t value) { this->m_value = value; } offset_t getValue() { return m_value; } bool insertIntoBuffer(AbstractByteBuffer* buf); bool readFromBuffer(AbstractByteBuffer* buf); offset_t getTotalOffset() { return m_bigOffset + m_smallOffset; } offset_t getBigOffset() { return m_bigOffset; } size_t getValueSize() { return m_valueSize; } protected: size_t m_id; size_t m_relativeToId; offset_t m_bigOffset; // offset of instruction in code offset_t m_smallOffset; size_t m_valueSize; offset_t m_value; friend class Stub; }; class Stub { public: enum STUB_PARAMS { NEW_EP, //LABEL_newEP DATA_RVA, //LABEL_dataRVA OEP, //LABEL_oldEP FUNC_GET_MODULE_RVA, FUNC_LOAD_LIB_RVA }; Stub() { } virtual ~Stub() { deleteParams(); } virtual bufsize_t getSize() const = 0; virtual const unsigned char* getData() const = 0; virtual offset_t getSignatureStart() const = 0; virtual offset_t getSignatureEnd() const = 0; virtual offset_t getDatastoreOffset() const = 0; ByteBuffer* createStubBuffer(); bool containsStub(AbstractByteBuffer *buf) const; size_t getParamsCount() { return m_params.size(); } offset_t getParamValue(size_t id) { if (this->m_params.find(id) == m_params.end()) { //No param with given ID return INVALID_ADDR; } return this->m_params[id]->getValue(); } bool setParam(size_t id, offset_t value) { if (this->m_params.find(id) == m_params.end()) { //No param with given ID return false; } this->m_params[id]->setValue(value); return true; } virtual bool readParams(AbstractByteBuffer* buf); protected: StubParam* getParam(size_t id) const { std::map::const_iterator itr = this->m_params.find(id); if (itr == m_params.end()) return NULL; return itr->second; } offset_t paramDistance(size_t idFrom, size_t idTo) { StubParam *param = this->getParam(idTo); StubParam *newEpParam = this->getParam(idFrom); if (param == NULL || newEpParam == NULL) return INVALID_ADDR; offset_t newEntry = newEpParam->getValue() + newEpParam->getValueSize(); offset_t oldEntry = param->getValue(); bufsize_t oldEntryOffset = param->getTotalOffset(); //toOffset offset_t dif = ((newEntry + oldEntryOffset) - oldEntry) * (-1); return dif; } offset_t getAbsoluteValue(StubParam *param); // autocalculate relative virtual bool fillParam(size_t id, AbstractByteBuffer* buf); virtual bool fillParams(AbstractByteBuffer* buf); virtual bool readParam(size_t id, AbstractByteBuffer* buf); ByteBuffer* bufferStubData(); virtual void createParams() = 0; virtual void deleteParams(); std::map m_params; }; ================================================ FILE: patcher/stub/Stub32.cpp ================================================ #include "Stub32.h" #include "Stub32Data.h" bufsize_t Stub32::getSize() const { return Stub32Data::size; } const unsigned char* Stub32::getData() const { return Stub32Data::data; } offset_t Stub32::getSignatureStart() const { return Stub32Data::pointers[2] + 1 + sizeof(DWORD); } offset_t Stub32::getSignatureEnd() const { return Stub32Data::pointers[3]; } offset_t Stub32::getDatastoreOffset() const { return Stub32Data::pointers[DATA_RVA]; } void Stub32::createParams() { this->m_params[NEW_EP] = new StubParam(NEW_EP, Stub32Data::pointers[0], 1, sizeof(DWORD)); this->m_params[DATA_RVA] = new StubParam(DATA_RVA, Stub32Data::pointers[1], 1, sizeof(DWORD)); this->m_params[OEP] = new StubParam(OEP, Stub32Data::pointers[2], 1, sizeof(DWORD) , NEW_EP); this->m_params[FUNC_LOAD_LIB_RVA] = new StubParam(FUNC_LOAD_LIB_RVA, Stub32Data::pointers[3], 1, sizeof(DWORD)); this->m_params[FUNC_GET_MODULE_RVA] = new StubParam(FUNC_GET_MODULE_RVA, Stub32Data::pointers[4], 1, sizeof(DWORD)); } ================================================ FILE: patcher/stub/Stub32.h ================================================ #pragma once #include "Stub.h" class Stub32 : public Stub { public: Stub32() : Stub() { createParams(); } virtual bufsize_t getSize() const; virtual const unsigned char* getData() const; virtual offset_t getSignatureStart() const; virtual offset_t getSignatureEnd() const; virtual offset_t getDatastoreOffset() const; protected: virtual void createParams(); }; ================================================ FILE: patcher/stub/Stub32Data.h ================================================ #include namespace Stub32Data { const unsigned char data[] = { 0xb8, 0x11, 0x11, 0x11, 0x11, 0xbb, 0x22, 0x22, 0x22, 0x22, 0xe8, 0x05, 0x00, 0x00, 0x00, 0xe9, 0x64, 0x56, 0x34, 0x12, 0x83, 0xc0, 0x0f, 0x8b, 0x3c, 0x24, 0x29, 0xc7, 0x01, 0xfb, 0xe8, 0x4a, 0x00, 0x00, 0x00, 0x85, 0xc0, 0x75, 0x01, 0xc3, 0x89, 0xc1, 0x51, 0xbe, 0x22, 0x22, 0x22, 0x22, 0x01, 0xfe, 0xff, 0x16, 0x85, 0xc0, 0x75, 0x0b, 0xe8, 0x3c, 0x00, 0x00, 0x00, 0x85, 0xc0, 0x75, 0xf7, 0xeb, 0xdb, 0x89, 0xc1, 0xe8, 0x23, 0x00, 0x00, 0x00, 0x85, 0xc0, 0x74, 0xd0, 0x50, 0x51, 0xbe, 0x22, 0x22, 0x22, 0x22, 0x01, 0xfe, 0xff, 0x16, 0x89, 0xc6, 0xe8, 0x0d, 0x00, 0x00, 0x00, 0x85, 0xc0, 0x75, 0x01, 0xc3, 0x85, 0xf6, 0x74, 0x02, 0x89, 0x30, 0xeb, 0xd6, 0xe8, 0x07, 0x00, 0x00, 0x00, 0x85, 0xc0, 0x74, 0x02, 0x01, 0xf8, 0xc3, 0x8b, 0x03, 0x83, 0xc3, 0x04, 0xc3 }; DWORD pointers[] = { 0x00, //LABEL_newEP 0x05, //LABEL_dataRVA 0x0f, //LABEL_oldEP 0x2b, //LABEL_loadLibrary 0x50 //LABEL_GetProcAddress }; const size_t size = sizeof(data); };//Stub32Data ================================================ FILE: patcher/stub/Stub64.cpp ================================================ #include "Stub64.h" #include "Stub64Data.h" bufsize_t Stub64::getSize() const { return Stub64Data::size; } const unsigned char* Stub64::getData() const { return Stub64Data::data; } offset_t Stub64::getSignatureStart() const { return Stub64Data::pointers[2] + 1 + sizeof(DWORD); } offset_t Stub64::getSignatureEnd() const { return Stub64Data::pointers[3]; } offset_t Stub64::getDatastoreOffset() const { return Stub64Data::pointers[DATA_RVA]; } void Stub64::createParams() { this->m_params[NEW_EP] = new StubParam(NEW_EP, Stub64Data::pointers[0], 3, sizeof(DWORD)); this->m_params[DATA_RVA] = new StubParam(DATA_RVA, Stub64Data::pointers[1], 3, sizeof(DWORD)); this->m_params[OEP] = new StubParam(OEP, Stub64Data::pointers[2], 1, sizeof(DWORD) , NEW_EP); this->m_params[FUNC_LOAD_LIB_RVA] = new StubParam(FUNC_LOAD_LIB_RVA, Stub64Data::pointers[3], 2, sizeof(DWORD), NEW_EP); this->m_params[FUNC_GET_MODULE_RVA] = new StubParam(FUNC_GET_MODULE_RVA, Stub64Data::pointers[4], 2, sizeof(DWORD), NEW_EP); } ================================================ FILE: patcher/stub/Stub64.h ================================================ #pragma once #include "Stub.h" class Stub64 : public Stub { public: Stub64() : Stub() { createParams(); } virtual bufsize_t getSize() const; virtual const unsigned char* getData() const; virtual offset_t getSignatureStart() const; virtual offset_t getSignatureEnd() const; virtual offset_t getDatastoreOffset() const; protected: virtual void createParams(); }; ================================================ FILE: patcher/stub/Stub64Data.h ================================================ #include namespace Stub64Data { const unsigned char data[] = { 0x48, 0xc7, 0xc0, 0x11, 0x11, 0x11, 0x11, 0x48, 0xc7, 0xc3, 0x22, 0x22, 0x22, 0x22, 0xe8, 0x05, 0x00, 0x00, 0x00, 0xe9, 0x60, 0x56, 0x34, 0x12, 0x48, 0x83, 0xc0, 0x13, 0x4c, 0x8b, 0x3c, 0x24, 0x49, 0x29, 0xc7, 0x4c, 0x01, 0xfb, 0xe8, 0x53, 0x00, 0x00, 0x00, 0x85, 0xc0, 0x75, 0x01, 0xc3, 0x48, 0x89, 0xc1, 0x49, 0x89, 0xde, 0x48, 0x8b, 0x1c, 0x24, 0xff, 0x15, 0xed, 0xa1, 0x05, 0x00, 0x48, 0x85, 0xc0, 0x4c, 0x89, 0xf3, 0x75, 0x0b, 0xe8, 0x3e, 0x00, 0x00, 0x00, 0x85, 0xc0, 0x75, 0xf7, 0xeb, 0xd3, 0x48, 0x89, 0xc1, 0xe8, 0x23, 0x00, 0x00, 0x00, 0x85, 0xc0, 0x74, 0xc7, 0x48, 0x89, 0xc2, 0xe8, 0x2e, 0x00, 0x00, 0x00, 0x48, 0x89, 0xc6, 0xe8, 0x0f, 0x00, 0x00, 0x00, 0x85, 0xc0, 0x75, 0x01, 0xc3, 0x48, 0x85, 0xf6, 0x74, 0x03, 0x48, 0x89, 0x30, 0xeb, 0xd5, 0xe8, 0x08, 0x00, 0x00, 0x00, 0x85, 0xc0, 0x74, 0x03, 0x4c, 0x01, 0xf8, 0xc3, 0x48, 0x31, 0xc0, 0x8b, 0x03, 0x48, 0x83, 0xc3, 0x04, 0xc3, 0x53, 0x48, 0x83, 0xec, 0x20, 0xff, 0x15, 0xb4, 0x0f, 0x00, 0x00, 0x48, 0x83, 0xc4, 0x20, 0x5b, 0xc3 }; DWORD pointers[] = { 0x00, 0x07, 0x13, 0x3a, 0x9a }; const size_t size = sizeof(data); };//Stub64Data ================================================ FILE: stub/hexf.cpp ================================================ #define _CRT_SECURE_NO_WARNINGS #include int main(int argc, char* argv[]) { if (argc < 2) { printf("No fileName supplied!\n"); return -1; } FILE *fp = fopen(argv[1], "rb"); if (fp == NULL) { printf("Unable to open the file!\n"); return -1; } int brk = 4; int i = 0; char c = 0; while(!feof(fp)) { c = fgetc (fp); if (i == brk) { i = 0; printf("\n"); } i++; printf("0x%2.2x, ", c & 0x0FF); } printf("0x90\n"); return 0; } ================================================ FILE: stub/stub32.asm ================================================ [bits 32] start: LABEL_newEP: mov EAX, 11111111h ; new EP LABEL_dataRVA: mov EBX, 22222222h ; data RVA call init after_init: LABEL_oldEP: jmp 12345678h ; oep init: add EAX, (after_init - start) mov EDI, [ESP] sub EDI, EAX ; ImageBase add EBX, EDI load_lib: call get_saved_rva TEST EAX, EAX JNZ SHORT load_next_lib RET load_next_lib: mov ECX, EAX push ECX LABEL_LoadLibrary: MOV ESI, 22222222h ADD ESI, EDI CALL [ESI] ; call LoadLibraryA test EAX, EAX jnz load_function skip_functions: ; if DLL not found, skip mapped call get_saved_value test eax,eax jne skip_functions jmp load_lib load_function: mov ECX, EAX call get_saved_rva TEST EAX, EAX JZ SHORT load_lib push EAX push ECX LABEL_GetProcAddress: MOV ESI, 22222222h ADD ESI, EDI CALL DWORD NEAR [ESI] ; call GetProcAddress mov ESI, EAX ; ESI <- Handle call get_saved_rva ; thunk to fill or to skip TEST EAX, EAX ; is thunk empty? jne overwrite_thunk ret ; malformed data, just finish... overwrite_thunk: TEST ESI, ESI ; is Handle Empty? je _end_load_function MOV [EAX], ESI _end_load_function: JMP SHORT load_function get_saved_rva: call get_saved_value test eax,eax jz _end_get_saved_rva ADD EAX, EDI ; ImgBase _end_get_saved_rva: ret get_saved_value: mov eax, dword [EBX] ADD EBX, 0X4 ret ;-------- ;Data: dd (LABEL_newEP - start) dd (LABEL_dataRVA - start) dd (LABEL_oldEP - start) dd (LABEL_LoadLibrary - start) dd (LABEL_GetProcAddress - start) ================================================ FILE: stub/stub64.asm ================================================ [bits 64] start: LABEL_newEP: mov rax, 11111111h ; new EP LABEL_dataRVA: mov rbx, 22222222h ; data RVA call init after_init: LABEL_oldEP: jmp 12345678h ; oep init: add rax, (after_init - start) mov r15, [rsp] sub r15, rax ;r15 -> ImageBase add rbx, r15 load_lib: call get_saved_rva TEST EAX, EAX JNZ SHORT load_next_lib RET load_next_lib: mov rcx, rax mov r14,rbx mov rbx,[rsp] LABEL_LoadLibrary: CALL QWORD NEAR [RIP+0X5A1ED] ; call LoadLibraryA test rax, rax mov rbx,r14 jnz load_function skip_functions: ; if DLL not found, skip mapped call get_saved_value test eax,eax jne skip_functions jmp load_lib load_function: mov rcx, rax call get_saved_rva TEST EAX, EAX JZ SHORT load_lib mov rdx, rax CALL getProc mov rsi, rax ; RSI <- Handle call get_saved_rva ; thunk to fill or to skip TEST EAX, EAX ; is thunk empty? jne overwrite_thunk ret ; malformed data, just finish... overwrite_thunk: TEST rsi, rsi ; is Handle Empty? je _end_load_function MOV [rax], rsi _end_load_function: JMP SHORT load_function get_saved_rva: call get_saved_value test eax,eax jz _end_get_saved_rva ADD rax, r15 ; ImgBase _end_get_saved_rva: ret get_saved_value: xor rax, rax mov eax, dword [rbx] ADD rbx, 0X4 ret ;>------ getProc: PUSH RBX SUB RSP, 0X20 LABEL_GetProcAddress: CALL QWORD NEAR [RIP+0XFB4] ;[KERNEL32.dll].GetProcAddress ADD RSP, 0X20 POP RBX RET ;<------- ;-------- ;Data: dd (LABEL_newEP - start) dd (LABEL_dataRVA - start) dd (LABEL_oldEP - start) dd (LABEL_LoadLibrary - start) dd (LABEL_GetProcAddress - start)