diff --git a/.github/workflows/build_wintools.yml b/.github/workflows/build_wintools.yml index 9b7f652..8629eef 100644 --- a/.github/workflows/build_wintools.yml +++ b/.github/workflows/build_wintools.yml @@ -2,7 +2,7 @@ name: build_tools on: push: {tags: ['v*'] } # Push events to matching v*, i.e. v1.0, v20.15.10 jobs: - build_libwinhook: + build_winexe_libwinhook: runs-on: windows-2019 # default batch, powershell steps: - name: pull and init @@ -10,20 +10,20 @@ jobs: with: {submodules: true} - name: add msbuild to path uses: microsoft/setup-msbuild@v1.1 - - name: build dllloader - run: .\tool\libwinhook\build_libwinhook.bat + - name: build winloader + run: .\project\winexe_winloader\release_msvc.bat - name: create a release uses: ncipollo/release-action@v1 with: - artifacts: "./tool/libwinhook/release/dllloader32.exe,./tool/libwinhook/x64/release/dllloader64.exe" + artifacts: "./project/winexe_winloader/build/winloader32.exe,./project/winexe_winloader/build/winloader64.exe" allowUpdates: "true" token: ${{ secrets.GITHUB_TOKEN }} - build_pytool_nuitkasingle: + build_pyexes: runs-on: windows-2019 # default batch, powershell strategy: matrix: - pytoolname: [bintext, ftextcvt] + pyexe_name: [bintext, ftext] steps: - name: pull and init uses: actions/checkout@v3 @@ -37,46 +37,13 @@ jobs: run: | python -m pip install nuitka zstandard python -m pip install python-docx - - name: build pytool single + - name: build single pyexe by nuitka run: | - cmd.exe /c ".\tool\${{ matrix.pytoolname }}\build_${{ matrix.pytoolname }}_nuitkasingle.bat" - move ".\tool\${{ matrix.pytoolname }}\bin\c${{ matrix.pytoolname }}.exe" ".\tool\${{ matrix.pytoolname }}\bin\c${{ matrix.pytoolname }}32.exe" + cmd.exe /c ".\project\pyexe_${{ matrix.pyexe_name }}\build_nuitka.bat" + move ".\project\pyexe_${{ matrix.pyexe_name }}\build\c${{ matrix.pyexe_name }}.exe" ".\project\pyexe_${{ matrix.pyexe_name }}\build\c${{ matrix.pyexe_name }}32.exe" - name: create a release uses: ncipollo/release-action@v1 with: - artifacts: "./tool/${{ matrix.pytoolname }}/bin/*.exe" + artifacts: "./project/pyexe_${{ matrix.pyexe_name }}/build/*.exe" allowUpdates: "true" - token: ${{ secrets.GITHUB_TOKEN }} - - build_pytool_nuitkamulti: - runs-on: windows-2019 # default batch, powershell - strategy: - matrix: - pytoolname: [bintext, ftextcvt] - steps: - - name: pull and init - uses: actions/checkout@v3 - with: {submodules: true} - - name: set python version - uses: actions/setup-python@v3 - with: - python-version: '3.7' - architecture: 'x86' - - name: make python enviroment - run: | - python -m pip install nuitka zstandard - python -m pip install python-docx - - name: build pytool directory - run: | - cmd.exe /c ".\tool\${{ matrix.pytoolname }}\build_${{ matrix.pytoolname }}_nuitkamulti.bat" - - name: pack files - run: | - move ".\tool\${{ matrix.pytoolname }}\bin\multi" ".\tool\${{ matrix.pytoolname }}\bin\c${{ matrix.pytoolname }}32_multi" - 7z a -t7z -mx5 c${{ matrix.pytoolname }}32_multi.7z ".\tool\${{ matrix.pytoolname }}\bin\c${{ matrix.pytoolname }}32_multi" - - name: create a release - uses: ncipollo/release-action@v1 - with: - artifacts: "*.7z" - allowUpdates: "true" - token: ${{ secrets.GITHUB_TOKEN }} - \ No newline at end of file + token: ${{ secrets.GITHUB_TOKEN }} \ No newline at end of file diff --git a/.gitignore b/.gitignore index d68467d..9352ea6 100644 --- a/.gitignore +++ b/.gitignore @@ -1,5 +1,4 @@ *.pyc -__pycache__ *.o *.obj *.log @@ -8,18 +7,13 @@ __pycache__ *.pdb *.ipdb *.exp +*.aps *.ilk +*.vcxproj.filters +*.vcxproj.user + .vs .vscodes -/tool/**/bin/* -/tool/**/x64/* -/tool/**/Debug/* -/tool/**/Release/* -/tool/**/**/x64/* -/tool/**/**/Release/* -/tool/**/**/Debug/* -/script/tmp/* -/src/**/release/* -/src/**/debug/* -/util/bin/** -/env/* \ No newline at end of file +__pycache__ + +project/**/build/* \ No newline at end of file diff --git a/.vscode/settings.json b/.vscode/settings.json new file mode 100644 index 0000000..e5a1fb3 --- /dev/null +++ b/.vscode/settings.json @@ -0,0 +1,5 @@ +{ + "files.associations": { + "winpe.h": "c" + } +} \ No newline at end of file diff --git a/README.md b/README.md index 601731a..77c1b8c 100644 --- a/README.md +++ b/README.md @@ -1,31 +1,29 @@ -# ReverseUtil +# ReverseTool -![GitHub tag (latest by date)](https://img.shields.io/github/v/tag/yurisizuku/reverseutil?color=green&label=ReverseUtil)![GitHub Workflow Status](https://img.shields.io/github/actions/workflow/status/YuriSizuku/ReverseUtil/build_wintools.yml?label=build_wintools) +![GitHub tag (latest by date)](https://img.shields.io/github/v/tag/yurisizuku/reversetool?color=green&label=ReverseTool)![GitHub Workflow Status](https://img.shields.io/github/actions/workflow/status/YuriSizuku/ReverseTool/build_wintools.yml?label=build_wintools) There are my tools for reversing. -The building example is in `./sln`, +The building example is in `./project`, as well as `Makefile` for `tcc`, `gcc` and `clang`. -## UTIL scripts and libraries +## Cross scripts and libraries -* `bintext.py`, for text exporting and importing, checking +* `libbintext.py`, for text exporting and importing, checking +* `librawtext.py`, some matching and statistic method for text * `libfont.py`, for extracting, building tile font, or generating font picture. -* `libtext.py`, some matching and statistic method for text -* `texture.py`, something about texture and picture convert -* `ftextcvt.py`, convert the `ftext` format made by `bintext.py` -* `cpcvt.py`, convert some strings encoding in file -* `listmagic.py`, list the files magic to analyze -* `shellcode.py`, some method for generating shellcode, such as parsing `coff` object file -* `bintext.h`, parser for `ftext` by `bintext.py` +* `libtexture.py`, something about texture and picture convert +* `libshellcode.py`, some method for generating shellcode, such as parsing `coff` object file +* `ftext.py`, convert the `ftext` format made by `bintext.py` +* `codepage.py`, convert some strings encoding in file ## Windows scripts and libraries -* `win_injectdll.py` , pre inject `dll` to a `exe` -* `win_console.js`, Allocate a console for game -* `win_file.js` , view information for both `CreateFile`, `ReadFile`, `WriteFile`, `fopen`,`fread`, `fwrite` -* `win_redirect.js`, redirect font, codepage, and paths in games * `winhook.h`, single file for dynamic hook functions, such as IAT hook, inline hook * `winpe.h`, single file for parsing windows PE structure, adjust RELOC, ADDRS, or IAT +* `windllin.py` , pre inject `dll` to a `exe` +* `winconsole.js`, Allocate a console for game +* `winfile.js` , view information for both `CreateFile`, `ReadFile`, `WriteFile`, `fopen`,`fread`, `fwrite` +* `winredirect.js`, redirect font, codepage, and paths in games -## Useful tools +## Windows Useful tools -* `dllloader.c`, a tool to start a exe with a `dll` injected, see [Release](https://github.com/YuriSizuku/ReverseUtil/releases) +* `win.c`, a tool to start a exe with a `dll` injected, see [Release](https://github.com/YuriSizuku/ReverseUtil/releases) diff --git a/project/pyexe_bintext/_env.bat b/project/pyexe_bintext/_env.bat new file mode 100644 index 0000000..4f66bb2 --- /dev/null +++ b/project/pyexe_bintext/_env.bat @@ -0,0 +1,7 @@ +::@echo off +set TARGET_NAME=bintext +set PYENV_NAME=pyenv +set PYENV_DIR=%~dp0build +set PYSRC_PATH=%~dp0..\..\src\py\libbintext.py +set OUT_DIR=%~dp0build +set ICON_PATH=%~dp0..\..\asset\default.ico \ No newline at end of file diff --git a/project/pyexe_bintext/build_nuitka.bat b/project/pyexe_bintext/build_nuitka.bat new file mode 100644 index 0000000..b9bc2bc --- /dev/null +++ b/project/pyexe_bintext/build_nuitka.bat @@ -0,0 +1,4 @@ +:: build single files +call %~dp0_env.bat +python -m pip install nuitka +nuitka --standalone --onefile --full-compat --show-progress "%PYSRC_PATH%" --windows-icon-from-ico="%ICON_PATH%" --output-dir="%OUT_DIR%" -o "c%TARGET_NAME%.exe" --assume-yes-for-downloads \ No newline at end of file diff --git a/project/pyexe_bintext/build_pyinstaller.bat b/project/pyexe_bintext/build_pyinstaller.bat new file mode 100644 index 0000000..ba07f09 --- /dev/null +++ b/project/pyexe_bintext/build_pyinstaller.bat @@ -0,0 +1,4 @@ +:: build by pyinstaller +call %~dp0_env.bat +python -m pip install pyinstaller +pyinstaller -F "%PYSRC_PATH%" --name "%TARGET_NAME%.exe" --distpath="%OUT_DIR%" --workpath="%OUT_DIR%/obj/pyinstaller" --specpath="%OUT_DIR%/obj/pyinstaller" --icon="%ICON_PATH%" --exclude-module=numpy --exclude-module=PIL --console --clean --noupx -y \ No newline at end of file diff --git a/project/pyexe_bintext/build_viapyenv.bat b/project/pyexe_bintext/build_viapyenv.bat new file mode 100644 index 0000000..d9ce1d0 --- /dev/null +++ b/project/pyexe_bintext/build_viapyenv.bat @@ -0,0 +1,11 @@ +::@echo off +:: use as build_viapyenv.bat path/to/xxx.bat + +call %~dp0_env.bat +if not exist "%PYENV_DIR%" mkdir "%PYENV_DIR%" + +pushd "%PYENV_DIR%" +python -m venv %PYENV_NAME% +cd %PYENV_NAME%\Scripts +call %1 +popd \ No newline at end of file diff --git a/project/pyexe_ftext/_env.bat b/project/pyexe_ftext/_env.bat new file mode 100644 index 0000000..0058ada --- /dev/null +++ b/project/pyexe_ftext/_env.bat @@ -0,0 +1,7 @@ +::@echo off +set TARGET_NAME=ftext +set PYENV_NAME=pyenv +set PYENV_DIR=%~dp0build +set PYSRC_PATH=%~dp0..\..\src\py\ftext.py +set OUT_DIR=%~dp0build +set ICON_PATH=%~dp0..\..\asset\default.ico \ No newline at end of file diff --git a/project/pyexe_ftext/build_nuitka.bat b/project/pyexe_ftext/build_nuitka.bat new file mode 100644 index 0000000..b9bc2bc --- /dev/null +++ b/project/pyexe_ftext/build_nuitka.bat @@ -0,0 +1,4 @@ +:: build single files +call %~dp0_env.bat +python -m pip install nuitka +nuitka --standalone --onefile --full-compat --show-progress "%PYSRC_PATH%" --windows-icon-from-ico="%ICON_PATH%" --output-dir="%OUT_DIR%" -o "c%TARGET_NAME%.exe" --assume-yes-for-downloads \ No newline at end of file diff --git a/project/pyexe_ftext/build_pyinstaller.bat b/project/pyexe_ftext/build_pyinstaller.bat new file mode 100644 index 0000000..ba07f09 --- /dev/null +++ b/project/pyexe_ftext/build_pyinstaller.bat @@ -0,0 +1,4 @@ +:: build by pyinstaller +call %~dp0_env.bat +python -m pip install pyinstaller +pyinstaller -F "%PYSRC_PATH%" --name "%TARGET_NAME%.exe" --distpath="%OUT_DIR%" --workpath="%OUT_DIR%/obj/pyinstaller" --specpath="%OUT_DIR%/obj/pyinstaller" --icon="%ICON_PATH%" --exclude-module=numpy --exclude-module=PIL --console --clean --noupx -y \ No newline at end of file diff --git a/project/pyexe_ftext/build_viapyenv.bat b/project/pyexe_ftext/build_viapyenv.bat new file mode 100644 index 0000000..06439b4 --- /dev/null +++ b/project/pyexe_ftext/build_viapyenv.bat @@ -0,0 +1,12 @@ +::@echo off +:: use as build_viapyenv.bat path/to/xxx.bat + +call %~dp0_env.bat +if not exist "%PYENV_DIR%" mkdir "%PYENV_DIR%" + +pushd "%PYENV_DIR%" +python -m venv %PYENV_NAME% +cd %PYENV_NAME%\Scripts +python -m pip install python-docx +call %1 +popd \ No newline at end of file diff --git a/project/windll_winhook/Makefile b/project/windll_winhook/Makefile new file mode 100644 index 0000000..6eb2352 --- /dev/null +++ b/project/windll_winhook/Makefile @@ -0,0 +1,116 @@ +# main config +LIBPREFIX?=./../../ +ARCH?=i686 +PREFIX?=./build + +CC:=clang +INCS:=-I$(LIBPREFIX)src/c/include +LIBDIRS:= +LIBS:=-luser32 -lgdi32 -lpsapi +CFLAGS:=-ffunction-sections\ + -fdata-sections -std=c99 +LDFLAGS:= + +# arch config +ifeq ($(ARCH), x86_64) +ARCH_POSTFIX:=64 +LIBDIRS+=-L$(LIBPREFIX)lib64 +CFLAGS+=-D_WIN64 +ifdef DEBUG +BUILD_POSTFIX:=64d +else +BUILD_POSTFIX:=64 +endif +else # x86 +ARCH_POSTFIX:=32 +LIBDIRS+=-L$(LIBPREFIX)lib32 +ifdef DEBUG +BUILD_POSTFIX:=32d +else +BUILD_POSTFIX:=32 +endif +endif + +# compiler config +ifneq (,$(findstring clang, $(CC))) +CFLAGS+=-target $(ARCH)-pc-windows-msvc \ + -D_CRT_SECURE_NO_DEPRECATE +LDFLAGS+= -Wl,/OPT:REF\ + -Wl,/DEF:src/libwinhook.def\ + -Wno-undefined-inline +else # mingw +CFLAGS+=-m$(ARCH_POSTFIX) \ + -fPIC\ + -fvisibility=hidden\ + -fgnu89-inline\ + -DWINPE_NOASM +ifneq (,$(findstring gcc, $(CC))) +LDFLAGS+=-lwinpthread \ + -static-libgcc \ + -static-libstdc++ \ + -Wl,-Bstatic,--whole-archive \ + -Wl,--no-whole-archive\ + -Wl,--gc-sections\ + -Wl,--enable-stdcall-fixup\ + -Wl,--kill-at +endif +endif + +# optimization config +ifdef DEBUG +CFLAGS+=-g -D_DEBUG +else +CFLAGS+=-Os +endif +LIBDIRS+=-L$(PREFIX) + +# system config +ifeq ($(shell echo ${OS}), Windows_NT) +DLL_EXT=.dll +EXE_EXT=.exe +else +DLL_EXT?=.so +EXE_EXT?= +endif + +# other config +ifneq (,$(findstring clang, $(CC))) +else +ifneq (,$(findstring gcc, $(CC))) +endif +endif + +all: prepare\ + libwinhook\ + libwinhook_test\ + helloexe\ + hellodll + +clean: + rm -rf $(PREFIX)/*libwinhook* + rm -rf $(PREFIX)/*hello* + rm -rf $(PREFIX)/*test* + +prepare: + @if ! [ -d $(PREFIX) ]; then mkdir -p $(PREFIX); fi + +libwinhook: src\libwinhook.c + @echo \#\#building $@ ... + $(CC) -shared $< \ + -o $(PREFIX)/$@$(BUILD_POSTFIX)$(DLL_EXT) \ + $(CFLAGS) $(LDFLAGS) $(INCS) $(LIBS) $(LIBDIRS) + +libwinhook_test: src\libwinhook_test.c + $(CC) $< \ + -o $(PREFIX)/$@$(BUILD_POSTFIX).exe \ + $(CFLAGS) $(LDFLAGS) $(INCS) $(LIBS) $(LIBDIRS) + +helloexe: src\helloexe.c + @echo \#\#building $@ ... + $(CC) $< -o $(PREFIX)/hello$(BUILD_POSTFIX).exe $(CFLAGS) -lgdi32 -luser32 + +hellodll: src\hellodll.c + @echo \#\#building $@ ... + $(CC) -shared $< -o $(PREFIX)/hello$(BUILD_POSTFIX).dll $(CFLAGS) -luser32 + +.PHONY: all clean prepare libwinhook helloexe hellodll \ No newline at end of file diff --git a/project/windll_winhook/libwinhook.sln b/project/windll_winhook/libwinhook.sln new file mode 100644 index 0000000..a9f4380 --- /dev/null +++ b/project/windll_winhook/libwinhook.sln @@ -0,0 +1,41 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio Version 17 +VisualStudioVersion = 17.2.32519.379 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "libwinhook", "libwinhook.vcxproj", "{EB7C50DF-0338-4C01-BA3E-ED41B4326BAA}" +EndProject +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "libwinhook_test", "libwinhook_test.vcxproj", "{9831FCEE-7281-403E-B9D5-7F65C59D7224}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|x64 = Debug|x64 + Debug|x86 = Debug|x86 + Release|x64 = Release|x64 + Release|x86 = Release|x86 + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {EB7C50DF-0338-4C01-BA3E-ED41B4326BAA}.Debug|x64.ActiveCfg = Debug|x64 + {EB7C50DF-0338-4C01-BA3E-ED41B4326BAA}.Debug|x64.Build.0 = Debug|x64 + {EB7C50DF-0338-4C01-BA3E-ED41B4326BAA}.Debug|x86.ActiveCfg = Debug|Win32 + {EB7C50DF-0338-4C01-BA3E-ED41B4326BAA}.Debug|x86.Build.0 = Debug|Win32 + {EB7C50DF-0338-4C01-BA3E-ED41B4326BAA}.Release|x64.ActiveCfg = Release|x64 + {EB7C50DF-0338-4C01-BA3E-ED41B4326BAA}.Release|x64.Build.0 = Release|x64 + {EB7C50DF-0338-4C01-BA3E-ED41B4326BAA}.Release|x86.ActiveCfg = Release|Win32 + {EB7C50DF-0338-4C01-BA3E-ED41B4326BAA}.Release|x86.Build.0 = Release|Win32 + {9831FCEE-7281-403E-B9D5-7F65C59D7224}.Debug|x64.ActiveCfg = Debug|x64 + {9831FCEE-7281-403E-B9D5-7F65C59D7224}.Debug|x64.Build.0 = Debug|x64 + {9831FCEE-7281-403E-B9D5-7F65C59D7224}.Debug|x86.ActiveCfg = Debug|Win32 + {9831FCEE-7281-403E-B9D5-7F65C59D7224}.Debug|x86.Build.0 = Debug|Win32 + {9831FCEE-7281-403E-B9D5-7F65C59D7224}.Release|x64.ActiveCfg = Release|x64 + {9831FCEE-7281-403E-B9D5-7F65C59D7224}.Release|x64.Build.0 = Release|x64 + {9831FCEE-7281-403E-B9D5-7F65C59D7224}.Release|x86.ActiveCfg = Release|Win32 + {9831FCEE-7281-403E-B9D5-7F65C59D7224}.Release|x86.Build.0 = Release|Win32 + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection + GlobalSection(ExtensibilityGlobals) = postSolution + SolutionGuid = {3D7EC52B-4831-44ED-BD63-68790FA7098F} + EndGlobalSection +EndGlobal diff --git a/tool/libwinhook/libwinhook/libwinhook.vcxproj b/project/windll_winhook/libwinhook.vcxproj similarity index 65% rename from tool/libwinhook/libwinhook/libwinhook.vcxproj rename to project/windll_winhook/libwinhook.vcxproj index d296906..3664e2d 100644 --- a/tool/libwinhook/libwinhook/libwinhook.vcxproj +++ b/project/windll_winhook/libwinhook.vcxproj @@ -1,4 +1,4 @@ - + @@ -18,13 +18,10 @@ x64 - - - 16.0 Win32Proj - {e14be7d3-25ed-44ad-8657-2d65874f3986} + {eb7c50df-0338-4c01-ba3e-ed41b4326baa} libwinhook 7.0 @@ -74,30 +71,42 @@ - true + $(SolutionDir)\build + $(SolutionDir)\build\obj\debug\i686 + $(ProjectName)32d - false + $(SolutionDir)\build + $(SolutionDir)\build\obj\release\i686 + $(ProjectName)32 - true + $(SolutionDir)\build + $(SolutionDir)\build\obj\debug\x86_64 + $(ProjectName)64d - false + $(SolutionDir)\build + $(SolutionDir)\build\obj\release\x86_64 + $(ProjectName)64 Level3 true - _CRT_SECURE_NO_WARNINGS; WIN32;_DEBUG;_CONSOLE;%(PreprocessorDefinitions) + _CRT_SECURE_NO_WARNINGS;WIN32;_DEBUG;LIBWINPE_EXPORTS;_WINDOWS;_USRDLL;%(PreprocessorDefinitions) true - ./../../../include - MultiThreaded + NotUsing + pch.h + ../../src/c/include;%(AdditionalIncludeDirectories) + StdCall Console true - Psapi.lib;%(AdditionalDependencies) + false + src/libwinhook.def + psapi.lib;%(AdditionalDependencies) @@ -106,34 +115,40 @@ true true true - _CRT_SECURE_NO_WARNINGS; WIN32;NDEBUG;_CONSOLE;%(PreprocessorDefinitions) + _CRT_SECURE_NO_WARNINGS;WIN32;NDEBUG;LIBWINPE_EXPORTS;_WINDOWS;_USRDLL;%(PreprocessorDefinitions) true - ./../../../include - MultiThreaded - OnlyExplicitInline - MaxSpeed + NotUsing + pch.h + ../../src/c/include;%(AdditionalIncludeDirectories) + StdCall Console true true true - Psapi.lib;%(AdditionalDependencies) + false + src/libwinhook.def + psapi.lib;%(AdditionalDependencies) Level3 true - _CRT_SECURE_NO_WARNINGS; _DEBUG;_CONSOLE;%(PreprocessorDefinitions) + _CRT_SECURE_NO_WARNINGS;_DEBUG;LIBWINPE_EXPORTS;_WINDOWS;_USRDLL;%(PreprocessorDefinitions) true - ./../../../include - MultiThreaded + NotUsing + pch.h + ../../src/c/include;%(AdditionalIncludeDirectories) + StdCall Console true - Psapi.lib;%(AdditionalDependencies) + false + src/libwinhook.def + psapi.lib;%(AdditionalDependencies) @@ -142,21 +157,26 @@ true true true - _CRT_SECURE_NO_WARNINGS; NDEBUG;_CONSOLE;%(PreprocessorDefinitions) + _CRT_SECURE_NO_WARNINGS;NDEBUG;LIBWINPE_EXPORTS;_WINDOWS;_USRDLL;%(PreprocessorDefinitions) true - ./../../../include - MultiThreaded - OnlyExplicitInline - MaxSpeed + NotUsing + pch.h + ../../src/c/include;%(AdditionalIncludeDirectories) + StdCall Console true true true - Psapi.lib;%(AdditionalDependencies) + false + src/libwinhook.def + psapi.lib;%(AdditionalDependencies) + + + diff --git a/tool/libwinpe/test/test.vcxproj b/project/windll_winhook/libwinhook_test.vcxproj similarity index 73% rename from tool/libwinpe/test/test.vcxproj rename to project/windll_winhook/libwinhook_test.vcxproj index 6fbe786..d2f9e3c 100644 --- a/tool/libwinpe/test/test.vcxproj +++ b/project/windll_winhook/libwinhook_test.vcxproj @@ -21,8 +21,8 @@ 16.0 Win32Proj - {e2b4ebf4-169a-473f-936e-d95da3e861a3} - test + {9831fcee-7281-403e-b9d5-7f65c59d7224} + libwinhook_test 7.0 @@ -71,16 +71,26 @@ - true - - - false + false + $(SolutionDir)\build\obj\debug\i686 + $(ProjectName)32d + $(SolutionDir)\build - true + false + $(SolutionDir)\build + $(SolutionDir)\build\obj\debug\x86_64 + $(ProjectName)64d + + + $(SolutionDir)\build + $(SolutionDir)\build\obj\release\i686 + $(ProjectName)32 - false + $(SolutionDir)\build\ + $(SolutionDir)\build\obj\release\x86_64 + $(ProjectName)64 @@ -88,13 +98,16 @@ true _CRT_SECURE_NO_WARNINGS;WIN32;_DEBUG;_CONSOLE;%(PreprocessorDefinitions) true - ./../../../include;%(AdditionalIncludeDirectories) + ../../src/c/include;%(AdditionalIncludeDirectories) Console true - %(AdditionalDependencies) + psapi.lib;%(AdditionalDependencies) + + _CRT_SECURE_NO_WARNINGS;%(PreprocessorDefinitions) + @@ -104,15 +117,18 @@ true _CRT_SECURE_NO_WARNINGS;WIN32;NDEBUG;_CONSOLE;%(PreprocessorDefinitions) true - ./../../../include;%(AdditionalIncludeDirectories) + ../../src/c/include;%(AdditionalIncludeDirectories) Console true true true - %(AdditionalDependencies) + psapi.lib;%(AdditionalDependencies) + + _CRT_SECURE_NO_WARNINGS;%(PreprocessorDefinitions) + @@ -120,13 +136,16 @@ true _CRT_SECURE_NO_WARNINGS;_DEBUG;_CONSOLE;%(PreprocessorDefinitions) true - ./../../../include;%(AdditionalIncludeDirectories) + ../../src/c/include;%(AdditionalIncludeDirectories) Console true - %(AdditionalDependencies) + psapi.lib;%(AdditionalDependencies) + + _CRT_SECURE_NO_WARNINGS;%(PreprocessorDefinitions) + @@ -136,18 +155,21 @@ true _CRT_SECURE_NO_WARNINGS;NDEBUG;_CONSOLE;%(PreprocessorDefinitions) true - ./../../../include;%(AdditionalIncludeDirectories) + ../../src/c/include;%(AdditionalIncludeDirectories) Console true true true - %(AdditionalDependencies) + psapi.lib;%(AdditionalDependencies) + + _CRT_SECURE_NO_WARNINGS;%(PreprocessorDefinitions) + - + diff --git a/project/windll_winhook/release_msvc.bat b/project/windll_winhook/release_msvc.bat new file mode 100644 index 0000000..4698ed6 --- /dev/null +++ b/project/windll_winhook/release_msvc.bat @@ -0,0 +1,2 @@ +msbuild %~dp0\libwinhook.sln -t:libwinhook:rebuild -p:configuration=release -p:Platform=x86 +msbuild %~dp0\libwinhook.sln -t:libwinhook:rebuild -p:configuration=release -p:Platform=x64 \ No newline at end of file diff --git a/tool/libwinhook/test_hellodll/hello_dll.c b/project/windll_winhook/src/hellodll.c similarity index 70% rename from tool/libwinhook/test_hellodll/hello_dll.c rename to project/windll_winhook/src/hellodll.c index 01c42dd..5b20425 100644 --- a/tool/libwinhook/test_hellodll/hello_dll.c +++ b/project/windll_winhook/src/hellodll.c @@ -1,21 +1,20 @@ -// dllmain.cpp : 定义 DLL 应用程序的入口点。 -#include - -BOOL APIENTRY DllMain( HMODULE hModule, - DWORD ul_reason_for_call, - LPVOID lpReserved - ) -{ - switch (ul_reason_for_call) - { - case DLL_PROCESS_ATTACH: - MessageBoxA(NULL, "hello world", "hello", 0); - break; - case DLL_THREAD_ATTACH: - case DLL_THREAD_DETACH: - case DLL_PROCESS_DETACH: - break; - } - return TRUE; -} - +#include + +BOOL APIENTRY DllMain( HMODULE hModule, + DWORD ul_reason_for_call, + LPVOID lpReserved + ) +{ + switch (ul_reason_for_call) + { + case DLL_PROCESS_ATTACH: + MessageBoxA(NULL, "hello world dll", "injected", 0); + break; + case DLL_THREAD_ATTACH: + case DLL_THREAD_DETACH: + case DLL_PROCESS_DETACH: + break; + } + return TRUE; +} + diff --git a/project/windll_winhook/src/helloexe.c b/project/windll_winhook/src/helloexe.c new file mode 100644 index 0000000..efbf97c --- /dev/null +++ b/project/windll_winhook/src/helloexe.c @@ -0,0 +1,74 @@ +#include +#define _UNICODE + +HWND hwnd; +LRESULT CALLBACK WndProc(HWND hwnd, UINT Msg, WPARAM wParam, LPARAM lParam); + +int CALLBACK wWinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, wchar_t * lpCmdLine, int nCmdShow) +{ + MSG Msg; + WNDCLASSEXW WndClsEx = {0}; + + WndClsEx.cbSize = sizeof (WNDCLASSEXW); + WndClsEx.style = CS_HREDRAW | CS_VREDRAW; + WndClsEx.lpfnWndProc = WndProc; + WndClsEx.hInstance = hInstance; + WndClsEx.hbrBackground = (HBRUSH)GetStockObject(WHITE_BRUSH); + WndClsEx.lpszClassName = L"HelloWorldClass"; + WndClsEx.hIconSm = LoadIcon(hInstance, IDI_APPLICATION); + + RegisterClassExW(&WndClsEx); + + hwnd = CreateWindowExW(WS_EX_OVERLAPPEDWINDOW, + L"HelloWorldClass", + (LPCWSTR)"Hello World", + WS_OVERLAPPEDWINDOW, + 100, + 120, + 400, + 200, + NULL, + NULL, + hInstance, + NULL); + + ShowWindow(hwnd, nCmdShow); + UpdateWindow(hwnd); + + while(GetMessage(&Msg, NULL, 0, 0)) + { + TranslateMessage(&Msg); + DispatchMessage(&Msg); + } + return 0; +} +LRESULT CALLBACK WndProc(HWND hwnd, UINT Msg, WPARAM wParam, LPARAM lParam) +{ + switch(Msg) + { + case WM_DESTROY: + PostQuitMessage(WM_QUIT); + break; + case WM_PAINT: + { + /* */ + PAINTSTRUCT ps; + HDC hdc; + RECT rc; + hdc = BeginPaint(hwnd, &ps); + + GetClientRect(hwnd, &rc); + SetTextColor(hdc, 0); + SetBkMode(hdc, TRANSPARENT); + DrawTextW(hdc, L"HELLO WORLD", -1, &rc, DT_CENTER|DT_SINGLELINE|DT_VCENTER); + + EndPaint(hwnd, &ps); + /* */ + break; + } + break; + default: + return DefWindowProc(hwnd, Msg, wParam, lParam); + } + return 0; +} \ No newline at end of file diff --git a/tool/libwinhook/libwinhook/libwinhook.c b/project/windll_winhook/src/libwinhook.c similarity index 97% rename from tool/libwinhook/libwinhook/libwinhook.c rename to project/windll_winhook/src/libwinhook.c index 5fa660d..02cde83 100644 --- a/tool/libwinhook/libwinhook/libwinhook.c +++ b/project/windll_winhook/src/libwinhook.c @@ -1,5 +1,5 @@ -#define WINHOOK_IMPLEMENTATION -#define WINHOOK_SHARED -#define WINHOOK_NOINLINEHOOK -#define WINHOOK_USESHELLCODE +#define WINHOOK_IMPLEMENTATION +#define WINHOOK_SHARED +#define WINHOOK_NOINLINEHOOK +#define WINHOOK_USESHELLCODE #include "winhook.h" \ No newline at end of file diff --git a/project/windll_winhook/src/libwinhook.def b/project/windll_winhook/src/libwinhook.def new file mode 100644 index 0000000..573e8a0 --- /dev/null +++ b/project/windll_winhook/src/libwinhook.def @@ -0,0 +1,13 @@ +EXPORTS +winhook_getprocess +winhook_iathookpe +winhook_injectdll +winhook_installconsole +winhook_patchmemoryex +winhook_patchmemorysex +winhook_patchmemorypattern +winhook_patchmemory1337ex +winhook_patchmemoryipsex +winhook_searchmemory +winhook_searchmemoryex +winhook_startexeinject diff --git a/tool/libwinhook/test/test_winhook.c b/project/windll_winhook/src/libwinhook_test.c similarity index 82% rename from tool/libwinhook/test/test_winhook.c rename to project/windll_winhook/src/libwinhook_test.c index 86a9a09..6732c53 100644 --- a/tool/libwinhook/test/test_winhook.c +++ b/project/windll_winhook/src/libwinhook_test.c @@ -66,28 +66,27 @@ void test_patchips() { printf("\n## test_patchips\n"); char pattern[256]; - uint8_t v1 = 1; - uint32_t v2 = 2; + uint32_t v[2] = {1, 2}; int res = 0; - size_t base = (size_t)&v1; + size_t base = (size_t)&v; - printf("v1(%p)=%x v2(%p)=%x\n", &v1, v1, &v2, v2); + printf("v[0](%p)=%x v[1](%p)=%x\n", &v[0], v[0], &v[1], v[1]); strncpy(pattern, "PATCH", 5); - uint8_t* p = pattern + 5; + uint8_t* p = (uint8_t*)(pattern + 5); *p++ = 0; *p++ = 0; *p++ = 0; // offset1 *p++ = 0; *p++ = 1;// size1 *p++ = 0xff; // patch1 - size_t offset = (size_t)&v2 - (size_t)&v1; - *p++ = (offset >> 16) & 0xff; *p++ = (offset >> 8) & 0xff; *p++ = offset&0xff; // offset2 + size_t offset = 4; + *p++ = (offset >> 16) & 0xff; *p++ = (offset >> 8) & 0xff; *p++ = offset & 0xff; // offset2 *p++ = 0; *p++ = 4; // size2 *p++ = 0x12; *p++ = 0xab; *p++ = 0xcd; *p++ = 0x09; // patch2 - strncpy(p, "EOF", 3); + strncpy((char*)p, "EOF", 3); puts(pattern); res = winhook_patchmemoryips(pattern, base); - printf("v1(%p)=%x v2(%p)=%x\n", &v1, v1, &v2, v2); + printf("v[0](%p)=%x v[1](%p)=%x\n", &v[0], v[0], &v[1], v[1]); assert(res == 5); - assert(v1 == 0xff); - assert(v2 == 0x09cdab12); + assert(v[0] == 0xff); + assert(v[1] == 0x09cdab12); } void test_searchpattern() @@ -119,7 +118,14 @@ void test_searchpattern2() void test_startexeinject() { printf("\n## test_startexeinject\n"); - DWORD pid = winhook_startexeinject("hello.exe", NULL, "hello.dll"); + DWORD pid = 0; +#ifdef _WIN64 + pid = winhook_startexeinject("hello64.exe", NULL, "hello64.dll"); + if(!pid) pid = winhook_startexeinject("hello64d.exe", NULL, "hello64d.dll"); +#else + pid = winhook_startexeinject("hello32.exe", NULL, "hello32.dll"); + if(!pid) pid = winhook_startexeinject("hello32d.exe", NULL, "hello32d.dll"); +#endif } void test_windyn() diff --git a/tool/libwinhook/Makefile b/project/windll_winpe/Makefile similarity index 74% rename from tool/libwinhook/Makefile rename to project/windll_winpe/Makefile index 8867a8b..43ecc54 100644 --- a/tool/libwinhook/Makefile +++ b/project/windll_winpe/Makefile @@ -1,12 +1,12 @@ # main config LIBPREFIX?=./../../ ARCH?=i686 -PREFIX?=./bin +PREFIX?=./build CC:=clang -INCS:=-I$(LIBPREFIX)include +INCS:=-I$(LIBPREFIX)src/c/include LIBDIRS:= -LIBS:=-luser32 -lgdi32 +LIBS:=-luser32 -lgdi32 -lpsapi CFLAGS:=-ffunction-sections\ -fdata-sections -std=c99 LDFLAGS:= @@ -36,6 +36,7 @@ ifneq (,$(findstring clang, $(CC))) CFLAGS+=-target $(ARCH)-pc-windows-msvc \ -D_CRT_SECURE_NO_DEPRECATE LDFLAGS+= -Wl,/OPT:REF\ + -Wl,/DEF:src/libwinpe.def\ -Wno-undefined-inline else # mingw CFLAGS+=-m$(ARCH_POSTFIX) \ @@ -80,26 +81,18 @@ endif endif all: prepare\ - libwinhook\ - dllloader + libwinpe clean: - rm -rf $(PREFIX)/*libwinhook* - rm -rf $(PREFIX)/*dllloader* + rm -rf $(PREFIX)/*libwinpe* prepare: @if ! [ -d $(PREFIX) ]; then mkdir -p $(PREFIX); fi -libwinhook: .\libwinhook\libwinhook.c +libwinpe: src\libwinpe.c @echo \#\#building $@ ... $(CC) -shared $< \ -o $(PREFIX)/$@$(BUILD_POSTFIX)$(DLL_EXT) \ $(CFLAGS) $(LDFLAGS) $(INCS) $(LIBS) $(LIBDIRS) -dllloader: .\dllloader\dllloader.c - @echo \#\#building $@ ... - $(CC) $< \ - -o $(PREFIX)/$@$(BUILD_POSTFIX)$(EXE_EXT) \ - $(CFLAGS) $(LDFLAGS) $(INCS) $(LIBS) $(LIBDIRS) - -.PHONY: all clean prepare libwinhook dllloader \ No newline at end of file +.PHONY: all clean prepare libwinpe \ No newline at end of file diff --git a/project/windll_winpe/libwinpe.sln b/project/windll_winpe/libwinpe.sln new file mode 100644 index 0000000..e7ccf54 --- /dev/null +++ b/project/windll_winpe/libwinpe.sln @@ -0,0 +1,31 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio Version 17 +VisualStudioVersion = 17.2.32519.379 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "libwinpe", "libwinpe.vcxproj", "{EB7C50DF-0338-4C01-BA3E-ED41B4326BAA}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|x64 = Debug|x64 + Debug|x86 = Debug|x86 + Release|x64 = Release|x64 + Release|x86 = Release|x86 + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {EB7C50DF-0338-4C01-BA3E-ED41B4326BAA}.Debug|x64.ActiveCfg = Debug|x64 + {EB7C50DF-0338-4C01-BA3E-ED41B4326BAA}.Debug|x64.Build.0 = Debug|x64 + {EB7C50DF-0338-4C01-BA3E-ED41B4326BAA}.Debug|x86.ActiveCfg = Debug|Win32 + {EB7C50DF-0338-4C01-BA3E-ED41B4326BAA}.Debug|x86.Build.0 = Debug|Win32 + {EB7C50DF-0338-4C01-BA3E-ED41B4326BAA}.Release|x64.ActiveCfg = Release|x64 + {EB7C50DF-0338-4C01-BA3E-ED41B4326BAA}.Release|x64.Build.0 = Release|x64 + {EB7C50DF-0338-4C01-BA3E-ED41B4326BAA}.Release|x86.ActiveCfg = Release|Win32 + {EB7C50DF-0338-4C01-BA3E-ED41B4326BAA}.Release|x86.Build.0 = Release|Win32 + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection + GlobalSection(ExtensibilityGlobals) = postSolution + SolutionGuid = {3D7EC52B-4831-44ED-BD63-68790FA7098F} + EndGlobalSection +EndGlobal diff --git a/tool/libwinhook/test_hellodll/test_hellodll.vcxproj b/project/windll_winpe/libwinpe.vcxproj similarity index 69% rename from tool/libwinhook/test_hellodll/test_hellodll.vcxproj rename to project/windll_winpe/libwinpe.vcxproj index 7cba1d5..c8a995b 100644 --- a/tool/libwinhook/test_hellodll/test_hellodll.vcxproj +++ b/project/windll_winpe/libwinpe.vcxproj @@ -21,8 +21,8 @@ 16.0 Win32Proj - {162fd21d-ea17-448a-9892-cad62d6849db} - testhellodll + {eb7c50df-0338-4c01-ba3e-ed41b4326baa} + libwinpe 7.0 @@ -71,35 +71,41 @@ - true - hello + $(SolutionDir)\build + $(SolutionDir)\build\obj\debug\i686 + $(ProjectName)32d - false - hello + $(SolutionDir)\build + $(SolutionDir)\build\obj\release\i686 + $(ProjectName)32 - true - hello + $(SolutionDir)\build + $(SolutionDir)\build\obj\debug\x86_64 + $(ProjectName)64d - false - hello + $(SolutionDir)\build + $(SolutionDir)\build\obj\release\x86_64 + $(ProjectName)64 Level3 true - WIN32;_DEBUG;TESTHELLODLL_EXPORTS;_WINDOWS;_USRDLL;%(PreprocessorDefinitions) + _CRT_SECURE_NO_WARNINGS;WIN32;_DEBUG;LIBWINPE_EXPORTS;_WINDOWS;_USRDLL;%(PreprocessorDefinitions) true NotUsing - - + pch.h + ../../src/c/include;%(AdditionalIncludeDirectories) + StdCall - Windows + Console true false + src/libwinpe.def @@ -108,35 +114,38 @@ true true true - WIN32;NDEBUG;TESTHELLODLL_EXPORTS;_WINDOWS;_USRDLL;%(PreprocessorDefinitions) + _CRT_SECURE_NO_WARNINGS;WIN32;NDEBUG;LIBWINPE_EXPORTS;_WINDOWS;_USRDLL;%(PreprocessorDefinitions) true NotUsing - - + pch.h + ../../src/c/include;%(AdditionalIncludeDirectories) + StdCall - Windows + Console true true true false + src/libwinpe.def Level3 true - _DEBUG;TESTHELLODLL_EXPORTS;_WINDOWS;_USRDLL;%(PreprocessorDefinitions) + _CRT_SECURE_NO_WARNINGS;_DEBUG;LIBWINPE_EXPORTS;_WINDOWS;_USRDLL;%(PreprocessorDefinitions) true NotUsing - - + pch.h + ../../src/c/include;%(AdditionalIncludeDirectories) + StdCall - Windows + Console true false - 5.01 + src/libwinpe.def @@ -145,23 +154,24 @@ true true true - NDEBUG;TESTHELLODLL_EXPORTS;_WINDOWS;_USRDLL;%(PreprocessorDefinitions) + _CRT_SECURE_NO_WARNINGS;NDEBUG;LIBWINPE_EXPORTS;_WINDOWS;_USRDLL;%(PreprocessorDefinitions) true NotUsing - - + pch.h + ../../src/c/include;%(AdditionalIncludeDirectories) + StdCall - Windows + Console true true true false - 5.01 + src/libwinpe.def - + diff --git a/project/windll_winpe/release_msvc.bat b/project/windll_winpe/release_msvc.bat new file mode 100644 index 0000000..f978a0b --- /dev/null +++ b/project/windll_winpe/release_msvc.bat @@ -0,0 +1,2 @@ +msbuild %~dp0\libwinpe.sln -t:libwinpe:rebuild -p:configuration=release -p:Platform=x86 +msbuild %~dp0\libwinpe.sln -t:libwinpe:rebuild -p:configuration=release -p:Platform=x64 \ No newline at end of file diff --git a/tool/libwinpe/libwinpe/libwinpe.c b/project/windll_winpe/src/libwinpe.c similarity index 59% rename from tool/libwinpe/libwinpe/libwinpe.c rename to project/windll_winpe/src/libwinpe.c index 9e4e607..edb9f21 100644 --- a/tool/libwinpe/libwinpe/libwinpe.c +++ b/project/windll_winpe/src/libwinpe.c @@ -1,3 +1,6 @@ #define WINPE_SHARED #define WINPE_IMPLEMENTATION +#ifdef _WIN64 +#define WINPE_NOASM +#endif #include "winpe.h" \ No newline at end of file diff --git a/tool/libwinpe/libwinpe/libwinpe.def b/project/windll_winpe/src/libwinpe.def similarity index 91% rename from tool/libwinpe/libwinpe/libwinpe.def rename to project/windll_winpe/src/libwinpe.def index 9fa0a76..105de8e 100644 --- a/tool/libwinpe/libwinpe/libwinpe.def +++ b/project/windll_winpe/src/libwinpe.def @@ -4,8 +4,10 @@ EXPORTS winpe_findkernel32 winpe_findloadlibrarya winpe_findspace + winpe_findmoduleaex winpe_imagebaseval winpe_imagesizeval + winpe_memfindexpcrc32 winpe_memFreeLibrary winpe_memFreeLibraryEx winpe_memGetProcAddress diff --git a/project/winexe_winloader/Makefile b/project/winexe_winloader/Makefile new file mode 100644 index 0000000..1855af1 --- /dev/null +++ b/project/winexe_winloader/Makefile @@ -0,0 +1,97 @@ +# main config +LIBPREFIX?=./../../ +ARCH?=i686 +PREFIX?=./build + +CC:=clang +INCS:=-I$(LIBPREFIX)src/c/include +LIBDIRS:= +LIBS:=-luser32 -lgdi32 -lpsapi +CFLAGS:=-ffunction-sections\ + -fdata-sections -std=c99 +LDFLAGS:= + +# arch config +ifeq ($(ARCH), x86_64) +ARCH_POSTFIX:=64 +LIBDIRS+=-L$(LIBPREFIX)lib64 +CFLAGS+=-D_WIN64 +ifdef DEBUG +BUILD_POSTFIX:=64d +else +BUILD_POSTFIX:=64 +endif +else # x86 +ARCH_POSTFIX:=32 +LIBDIRS+=-L$(LIBPREFIX)lib32 +ifdef DEBUG +BUILD_POSTFIX:=32d +else +BUILD_POSTFIX:=32 +endif +endif + +# compiler config +ifneq (,$(findstring clang, $(CC))) +CFLAGS+=-target $(ARCH)-pc-windows-msvc \ + -D_CRT_SECURE_NO_DEPRECATE +LDFLAGS+= -Wl,/OPT:REF\ + -Wno-undefined-inline +else # mingw +CFLAGS+=-m$(ARCH_POSTFIX) \ + -fPIC\ + -fvisibility=hidden\ + -fgnu89-inline\ + -DWINPE_NOASM +ifneq (,$(findstring gcc, $(CC))) +LDFLAGS+=-lwinpthread \ + -static-libgcc \ + -static-libstdc++ \ + -Wl,-Bstatic,--whole-archive \ + -Wl,--no-whole-archive\ + -Wl,--gc-sections\ + -Wl,--enable-stdcall-fixup\ + -Wl,--kill-at +endif +endif + +# optimization config +ifdef DEBUG +CFLAGS+=-g -D_DEBUG +else +CFLAGS+=-Os +endif +LIBDIRS+=-L$(PREFIX) + +# system config +ifeq ($(shell echo ${OS}), Windows_NT) +DLL_EXT=.dll +EXE_EXT=.exe +else +DLL_EXT?=.so +EXE_EXT?= +endif + +# other config +ifneq (,$(findstring clang, $(CC))) +else +ifneq (,$(findstring gcc, $(CC))) +endif +endif + +all: prepare\ + winloader + +clean: + rm -rf $(PREFIX)/*winloader* + +prepare: + @if ! [ -d $(PREFIX) ]; then mkdir -p $(PREFIX); fi + +winloader: src\winloader.c + @echo \#\#building $@ ... + $(CC) $< \ + -o $(PREFIX)/$@$(BUILD_POSTFIX)$(EXE_EXT) \ + $(CFLAGS) $(LDFLAGS) $(INCS) $(LIBS) $(LIBDIRS) + +.PHONY: all clean prepare winloader \ No newline at end of file diff --git a/project/winexe_winloader/release_msvc.bat b/project/winexe_winloader/release_msvc.bat new file mode 100644 index 0000000..a74d155 --- /dev/null +++ b/project/winexe_winloader/release_msvc.bat @@ -0,0 +1,2 @@ +msbuild %~dp0\winloader.sln -t:winloader:rebuild -p:configuration=release -p:Platform=x86 +msbuild %~dp0\winloader.sln -t:winloader:rebuild -p:configuration=release -p:Platform=x64 \ No newline at end of file diff --git a/tool/libwinhook/dllloader/resource.h b/project/winexe_winloader/src/resource.h similarity index 100% rename from tool/libwinhook/dllloader/resource.h rename to project/winexe_winloader/src/resource.h diff --git a/tool/libwinhook/dllloader/dllloader.aps b/project/winexe_winloader/src/winloader.aps similarity index 98% rename from tool/libwinhook/dllloader/dllloader.aps rename to project/winexe_winloader/src/winloader.aps index 186650e..83fd7e6 100644 Binary files a/tool/libwinhook/dllloader/dllloader.aps and b/project/winexe_winloader/src/winloader.aps differ diff --git a/tool/libwinhook/dllloader/dllloader.c b/project/winexe_winloader/src/winloader.c similarity index 80% rename from tool/libwinhook/dllloader/dllloader.c rename to project/winexe_winloader/src/winloader.c index ee89ae1..4a50132 100644 --- a/tool/libwinhook/dllloader/dllloader.c +++ b/project/winexe_winloader/src/winloader.c @@ -13,12 +13,12 @@ int main(int argc, char *argv[]) char *cmdstr = NULL; char dllpath[MAX_PATH] = {0}; - printf("dllloader v0.1, developed by devseed\n" + printf("winloader v0.1, developed by devseed\n" "usage:\n" - "dllloader // if the name is xxx_yyy.exe, start yyy.exe\n" - "dllloader exepath, cmdstr // will be null, dll has the same name as exe\n" - "dllloader exepath dllpath\n" - "dllloader exepath dllpath cmdstr\n\n" + "winloader // if the name is xxx_yyy.exe, start yyy.exe\n" + "winloader exepath, cmdstr // will be null, dll has the same name as exe\n" + "winloader exepath dllpath\n" + "winloader exepath dllpath cmdstr\n\n" ); switch (argc) diff --git a/tool/libwinhook/dllloader/dllloader.rc b/project/winexe_winloader/src/winloader.rc similarity index 100% rename from tool/libwinhook/dllloader/dllloader.rc rename to project/winexe_winloader/src/winloader.rc diff --git a/project/winexe_winloader/winloader.sln b/project/winexe_winloader/winloader.sln new file mode 100644 index 0000000..f9654d9 --- /dev/null +++ b/project/winexe_winloader/winloader.sln @@ -0,0 +1,31 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio Version 17 +VisualStudioVersion = 17.2.32519.379 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "winloader", "winloader.vcxproj", "{9831FCEE-7281-403E-B9D5-7F65C59D7224}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|x64 = Debug|x64 + Debug|x86 = Debug|x86 + Release|x64 = Release|x64 + Release|x86 = Release|x86 + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {9831FCEE-7281-403E-B9D5-7F65C59D7224}.Debug|x64.ActiveCfg = Debug|x64 + {9831FCEE-7281-403E-B9D5-7F65C59D7224}.Debug|x64.Build.0 = Debug|x64 + {9831FCEE-7281-403E-B9D5-7F65C59D7224}.Debug|x86.ActiveCfg = Debug|Win32 + {9831FCEE-7281-403E-B9D5-7F65C59D7224}.Debug|x86.Build.0 = Debug|Win32 + {9831FCEE-7281-403E-B9D5-7F65C59D7224}.Release|x64.ActiveCfg = Release|x64 + {9831FCEE-7281-403E-B9D5-7F65C59D7224}.Release|x64.Build.0 = Release|x64 + {9831FCEE-7281-403E-B9D5-7F65C59D7224}.Release|x86.ActiveCfg = Release|Win32 + {9831FCEE-7281-403E-B9D5-7F65C59D7224}.Release|x86.Build.0 = Release|Win32 + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection + GlobalSection(ExtensibilityGlobals) = postSolution + SolutionGuid = {5B8899E9-9100-4C1D-B5F7-415D0C1E31A3} + EndGlobalSection +EndGlobal diff --git a/tool/libwinhook/test/test.vcxproj b/project/winexe_winloader/winloader.vcxproj similarity index 70% rename from tool/libwinhook/test/test.vcxproj rename to project/winexe_winloader/winloader.vcxproj index fe075d9..24c74da 100644 --- a/tool/libwinhook/test/test.vcxproj +++ b/project/winexe_winloader/winloader.vcxproj @@ -1,4 +1,4 @@ - + @@ -18,16 +18,12 @@ x64 - - - 16.0 Win32Proj - {ac905c95-1311-4798-8576-f1a08cce259f} - test + {9831fcee-7281-403e-b9d5-7f65c59d7224} + winloader 7.0 - test @@ -75,16 +71,26 @@ - false - - - false + false + $(SolutionDir)\build\obj\debug\i686 + $(ProjectName)32d + $(SolutionDir)\build - false + false + $(SolutionDir)\build + $(SolutionDir)\build\obj\debug\x86_64 + $(ProjectName)64d + + + $(SolutionDir)\build + $(SolutionDir)\build\obj\release\i686 + $(ProjectName)32 - false + $(SolutionDir)\build\ + $(SolutionDir)\build\obj\release\x86_64 + $(ProjectName)64 @@ -92,13 +98,16 @@ true _CRT_SECURE_NO_WARNINGS;WIN32;_DEBUG;_CONSOLE;%(PreprocessorDefinitions) true - ./../../../include + ../../src/c/include;%(AdditionalIncludeDirectories) Console true - Psapi.lib;%(AdditionalDependencies) + psapi.lib;%(AdditionalDependencies) + + _CRT_SECURE_NO_WARNINGS;%(PreprocessorDefinitions) + @@ -106,17 +115,20 @@ true true true - _CRT_SECURE_NO_WARNINGS;WINHOOK_NOINLINEHOOK;WIN32;NDEBUG;_CONSOLE;%(PreprocessorDefinitions) + _CRT_SECURE_NO_WARNINGS;WIN32;NDEBUG;_CONSOLE;%(PreprocessorDefinitions) true - ./../../../include + ../../src/c/include;%(AdditionalIncludeDirectories) Console true true true - Psapi.lib;%(AdditionalDependencies) + psapi.lib;%(AdditionalDependencies) + + _CRT_SECURE_NO_WARNINGS;%(PreprocessorDefinitions) + @@ -124,13 +136,16 @@ true _CRT_SECURE_NO_WARNINGS;_DEBUG;_CONSOLE;%(PreprocessorDefinitions) true - ./../../../include + ../../src/c/include;%(AdditionalIncludeDirectories) Console true - Psapi.lib;%(AdditionalDependencies) + psapi.lib;%(AdditionalDependencies) + + _CRT_SECURE_NO_WARNINGS;%(PreprocessorDefinitions) + @@ -138,18 +153,27 @@ true true true - _CRT_SECURE_NO_WARNINGS;WINHOOK_NOINLINEHOOK;NDEBUG;_CONSOLE;%(PreprocessorDefinitions) + _CRT_SECURE_NO_WARNINGS;NDEBUG;_CONSOLE;%(PreprocessorDefinitions) true - ./../../../include + ../../src/c/include;%(AdditionalIncludeDirectories) Console true true true - Psapi.lib;%(AdditionalDependencies) + psapi.lib;%(AdditionalDependencies) + + _CRT_SECURE_NO_WARNINGS;%(PreprocessorDefinitions) + + + + + + + diff --git a/script/minor/listmagic.py b/script/minor/listmagic.py deleted file mode 100644 index 34182ae..0000000 --- a/script/minor/listmagic.py +++ /dev/null @@ -1,32 +0,0 @@ -import csv -import os -import sys - -def read_maigic(fp): - chars = [] - i = 0 - while True: - c = fp.read(1) - if c.isalnum() is False: - return "".join(chars) - if c==b'\0' or i>10 : - return "".join(chars) - chars.append(chr(c[0])) - i += 1 - -if __name__ == "__main__": - arr = [] - for root, dirs, files in os.walk(sys.argv[1]): - for name in files: - path = os.path.join(root, name) - relpath = os.path.relpath(path, sys.argv[1]) - print(relpath) - with open(path, 'rb') as fp: - magic = read_maigic(fp) - if magic == [] or magic == "": magic = os.path.splitext(path)[1] - fsize = os.path.getsize(path) - print(relpath, magic, fsize) - arr.append((relpath, magic, fsize)) - with open(os.path.basename(sys.argv[1]+"_magiclist.csv"), 'w', newline='') as fp: - w = csv.writer(fp) - w.writerows(arr) \ No newline at end of file diff --git a/script/minor/png2rgba.py b/script/minor/png2rgba.py deleted file mode 100644 index 0348df0..0000000 --- a/script/minor/png2rgba.py +++ /dev/null @@ -1,16 +0,0 @@ -import cv2 -import os -import numpy as np - -outdir = "out" -if not os.path.exists(outdir): os.os.mkdir(outdir) -for file in os.listdir("./"): - if os.path.splitext(file)[1] != '.png': - continue - img = cv2.imread(file, cv2.IMREAD_UNCHANGED) - if img.shape[2] < 4: - imgb, imgg, imgr = cv2.split(img) - imga = np.ones(imgb.shape, dtype=imgb.dtype) * 255 - img = cv2.merge((imgb, imgg, imgr, imga)) - cv2.imwrite(os.path.join(outdir, file), img[:, : , [2,1,0,3]]) - print(f"convert {file} done!") \ No newline at end of file diff --git a/include/windyn.h b/src/c/include/windyn.h similarity index 95% rename from include/windyn.h rename to src/c/include/windyn.h index 08be319..dbc58b3 100644 --- a/include/windyn.h +++ b/src/c/include/windyn.h @@ -1,765 +1,767 @@ -/* -windows api function pointer define, -functions or macros for dynamic bindings - v0.1.3, developed by devseed -*/ - -#ifndef _WINDYN_H -#define _WINDYN_H -#include -#include -#include - -#ifndef WINDYNDEF -#ifdef WINDYN_STATIC -#define WINDYNDEF static -#else -#define WINDYNDEF extern -#endif -#endif - -#ifndef WINDYN_SHARED -#define WINDYN_EXPORT -#else -#ifdef _WIN32 -#define WINDYN_EXPORT __declspec(dllexport) -#else -#define WINDYN_EXPORT __attribute__((visibility("default"))) -#endif -#endif - -#ifndef INLINE -#if defined(_MSC_VER) -#define INLINE __forceinline -#else // tcc, gcc not support inline export ... -#define INLINE -#endif -#endif - -#ifdef __cplusplus -extern "C" { -#endif - -// function pointer declear -typedef HMODULE (WINAPI* PFN_LoadLibraryA)( - LPCSTR lpLibFileName -); - -typedef FARPROC (WINAPI* PFN_GetProcAddress)( - HMODULE hModule, - LPCSTR lpProcName -); - -typedef HMODULE (WINAPI *PFN_GetModuleHandleA)( - LPCSTR lpModuleName -); - -typedef LPVOID (WINAPI *PFN_VirtualAllocEx)( - HANDLE hProcess, - LPVOID lpAddress, - SIZE_T dwSize, - DWORD flAllocationType, - DWORD flProtect -); - -typedef BOOL (WINAPI *PFN_VirtualFreeEx)( - HANDLE hProcess, - LPVOID lpAddress, - SIZE_T dwSize, - DWORD dwFreeType -); - -typedef BOOL (WINAPI *PFN_VirtualProtectEx)( - HANDLE hProcess, - LPVOID lpAddress, - SIZE_T dwSize, - DWORD flNewProtect, - PDWORD lpflOldProtect -); - -typedef BOOL (WINAPI *PFN_CreateProcessA)( - LPCSTR lpApplicationName, - LPSTR lpCommandLine, - LPSECURITY_ATTRIBUTES lpProcessAttributes, - LPSECURITY_ATTRIBUTES lpThreadAttributes, - BOOL bInheritHandles, - DWORD dwCreationFlags, - LPVOID lpEnvironment, - LPCSTR lpCurrentDirectory, - LPSTARTUPINFOA lpStartupInfo, - LPPROCESS_INFORMATION lpProcessInformation -); - -typedef HANDLE (WINAPI *PFN_OpenProcess)( - DWORD dwDesiredAccess, - BOOL bInheritHandle, - DWORD dwProcessId -); - -typedef HANDLE (WINAPI *PFN_GetCurrentProcess)( - VOID -); - -typedef BOOL (WINAPI *PFN_ReadProcessMemory)( - HANDLE hProcess, - LPCVOID lpBaseAddress, - LPVOID lpBuffer, - SIZE_T nSize, - SIZE_T* lpNumberOfBytesRead -); - -typedef BOOL (WINAPI *PFN_WriteProcessMemory)( - HANDLE hProcess, - LPVOID lpBaseAddress, - LPCVOID lpBuffer, - SIZE_T nSize, - SIZE_T* lpNumberOfBytesWritten -); - -typedef HANDLE (WINAPI *PFN_CreateRemoteThread)( - HANDLE hProcess, - LPSECURITY_ATTRIBUTES lpThreadAttributes, - SIZE_T dwStackSize, - LPTHREAD_START_ROUTINE lpStartAddress, - LPVOID lpParameter, - DWORD dwCreationFlags, - LPDWORD lpThreadId -); - -typedef HANDLE (WINAPI *PFN_GetCurrentThread)( - VOID -); - -typedef DWORD (WINAPI *PFN_SuspendThread)( - HANDLE hThread -); - -typedef DWORD (WINAPI *PFN_ResumeThread)( - HANDLE hThread -); - -typedef BOOL (WINAPI *PFN_GetThreadContext)( - HANDLE hThread, - LPCONTEXT lpContext -); - -typedef BOOL (WINAPI *PFN_SetThreadContext)( - HANDLE hThread, - CONST CONTEXT* lpContext -); - -typedef DWORD (WINAPI *PFN_WaitForSingleObject)( - HANDLE hHandle, - DWORD dwMilliseconds -); - -typedef BOOL (WINAPI *PFN_CloseHandle)( - HANDLE hObject -); - -typedef HANDLE (WINAPI *PFN_CreateToolhelp32Snapshot)( - DWORD dwFlags, - DWORD th32ProcessID -); - -typedef BOOL (WINAPI *PFN_Process32First)( - HANDLE hSnapshot, - LPPROCESSENTRY32 lppe -); - -typedef BOOL (WINAPI *PFN_Process32Next)( - HANDLE hSnapshot, - LPPROCESSENTRY32 lppe -); - -typedef NTSTATUS (NTAPI * PFN_NtQueryInformationProcess)( - IN HANDLE ProcessHandle, - IN PROCESSINFOCLASS ProcessInformationClass, - OUT PVOID ProcessInformation, - IN ULONG ProcessInformationLength, - OUT PULONG ReturnLength -); - -// util inline functions and macro declear -#define WINDYN_FINDEXP(mempe, funcname, exp)\ -{\ - PIMAGE_DOS_HEADER pDosHeader = (PIMAGE_DOS_HEADER)mempe;\ - PIMAGE_NT_HEADERS pNtHeader = (PIMAGE_NT_HEADERS)\ - ((uint8_t*)mempe + pDosHeader->e_lfanew);\ - PIMAGE_FILE_HEADER pFileHeader = &pNtHeader->FileHeader;\ - PIMAGE_OPTIONAL_HEADER pOptHeader = &pNtHeader->OptionalHeader;\ - PIMAGE_DATA_DIRECTORY pDataDirectory = pOptHeader->DataDirectory;\ - PIMAGE_DATA_DIRECTORY pExpEntry =\ - &pDataDirectory[IMAGE_DIRECTORY_ENTRY_EXPORT];\ - PIMAGE_EXPORT_DIRECTORY pExpDescriptor =\ - (PIMAGE_EXPORT_DIRECTORY)((uint8_t*)mempe + pExpEntry->VirtualAddress);\ - WORD* ordrva = (WORD*)((uint8_t*)mempe\ - + pExpDescriptor->AddressOfNameOrdinals);\ - DWORD* namerva = (DWORD*)((uint8_t*)mempe\ - + pExpDescriptor->AddressOfNames);\ - DWORD* funcrva = (DWORD*)((uint8_t*)mempe\ - + pExpDescriptor->AddressOfFunctions);\ - if ((size_t)funcname <= MAXWORD)\ - {\ - WORD ordbase = LOWORD(pExpDescriptor->Base) - 1;\ - WORD funcord = LOWORD(funcname);\ - exp = (void*)((uint8_t*)mempe + funcrva[ordrva[funcord - ordbase]]);\ - }\ - else\ - {\ - for (DWORD i = 0; i < pExpDescriptor->NumberOfNames; i++)\ - {\ - LPCSTR curname = (LPCSTR)((uint8_t*)mempe + namerva[i]);\ - if (windyn_stricmp(curname, funcname) == 0)\ - {\ - exp = (void*)((uint8_t*)mempe + funcrva[ordrva[i]]); \ - break;\ - }\ - }\ - }\ -} - -#define WINDYN_FINDMODULE(peb, modulename, hmod)\ -{\ - typedef struct _LDR_ENTRY \ - {\ - LIST_ENTRY InLoadOrderLinks; \ - LIST_ENTRY InMemoryOrderLinks;\ - LIST_ENTRY InInitializationOrderLinks;\ - PVOID DllBase;\ - PVOID EntryPoint;\ - ULONG SizeOfImage;\ - UNICODE_STRING FullDllName;\ - UNICODE_STRING BaseDllName;\ - ULONG Flags;\ - USHORT LoadCount;\ - USHORT TlsIndex;\ - union\ - {\ - LIST_ENTRY HashLinks;\ - struct\ - {\ - PVOID SectionPointer;\ - ULONG CheckSum;\ - };\ - };\ - ULONG TimeDateStamp;\ - } LDR_ENTRY, * PLDR_ENTRY; \ - PLDR_ENTRY ldrentry = NULL;\ - PPEB_LDR_DATA ldr = NULL;\ - if (!peb)\ - {\ - PTEB teb = NtCurrentTeb();\ - if(sizeof(size_t)>4) peb = *(PPEB*)((uint8_t*)teb + 0x60);\ - else peb = *(PPEB*)((uint8_t*)teb + 0x30);\ - }\ - if(sizeof(size_t)>4) ldr = *(PPEB_LDR_DATA*)((uint8_t*)peb + 0x18);\ - else ldr = *(PPEB_LDR_DATA*)((uint8_t*)peb + 0xC);\ - ldrentry = (PLDR_ENTRY)((size_t)\ - ldr->InMemoryOrderModuleList.Flink - 2 * sizeof(size_t));\ - if (!modulename)\ - {\ - hmod = ldrentry->DllBase;\ - }\ - else\ - {\ - while (ldrentry->InMemoryOrderLinks.Flink != \ - ldr->InMemoryOrderModuleList.Flink)\ - {\ - PUNICODE_STRING ustr = &ldrentry->FullDllName; \ - int i; \ - for (i = ustr->Length / 2 - 1; i > 0 && ustr->Buffer[i] != '\\'; i--); \ - if (ustr->Buffer[i] == '\\') i++; \ - if (windyn_stricmp2(modulename, ustr->Buffer + i) == 0)\ - {\ - hmod = ldrentry->DllBase; \ - break; \ - }\ - ldrentry = (PLDR_ENTRY)((size_t)\ - ldrentry->InMemoryOrderLinks.Flink - 2 * sizeof(size_t)); \ - }\ - }\ -} - -#define WINDYN_FINDKERNEL32(kernel32)\ -{\ - PPEB peb = NULL;\ - char name_kernel32[] = { 'k', 'e', 'r', 'n', 'e', 'l', '3', '2', '.', 'd', 'l', 'l', '\0' }; \ - WINDYN_FINDMODULE(peb, name_kernel32, kernel32);\ -} - -#define WINDYN_FINDLOADLIBRARYA(kernel32, pfnLoadLibraryA)\ -{\ - char name_LoadLibraryA[] = { 'L', 'o', 'a', 'd', 'L', 'i', 'b', 'r', 'a', 'r', 'y', 'A', '\0' };\ - WINDYN_FINDEXP((void*)kernel32, name_LoadLibraryA, pfnLoadLibraryA);\ -}\ - -#define WINDYN_FINDGETPROCADDRESS(kernel32, pfnGetProcAddress)\ -{\ - char name_GetProcAddress[] = { 'G', 'e', 't', 'P', 'r', 'o', 'c', 'A', 'd', 'd', 'r', 'e', 's', 's', '\0' }; \ - WINDYN_FINDEXP((void*)kernel32, name_GetProcAddress, pfnGetProcAddress);\ -} - -// stdc inline functions declear -WINDYNDEF WINDYN_EXPORT -int windyn_strlen(const char* str1); - -WINDYNDEF WINDYN_EXPORT -int windyn_stricmp(const char* str1, const char* str2); - -WINDYNDEF WINDYN_EXPORT -INLINE int windyn_stricmp2(const char* str1, const wchar_t* str2); - -WINDYNDEF WINDYN_EXPORT -INLINE int windyn_wcsicmp(const wchar_t* str1, const wchar_t* str2); - -WINDYNDEF WINDYN_EXPORT -INLINE void* windyn_memset(void* buf, int ch, size_t n); - -WINDYNDEF WINDYN_EXPORT -INLINE void* windyn_memcpy(void* dst, const void* src, size_t n); - -// winapi inline functions declear -WINDYNDEF WINDYN_EXPORT -INLINE HMODULE WINAPI windyn_GetModuleHandleA( - LPCSTR lpModuleName -); - -WINDYNDEF WINDYN_EXPORT -INLINE HMODULE WINAPI windyn_LoadLibraryA( - LPCSTR lpLibFileName -); - -WINDYNDEF WINDYN_EXPORT -INLINE FARPROC WINAPI windyn_GetProcAddress( - HMODULE hModule, - LPCSTR lpProcName -); - -WINDYNDEF WINDYN_EXPORT -INLINE LPVOID WINAPI windyn_VirtualAllocEx( - HANDLE hProcess, - LPVOID lpAddress, - SIZE_T dwSize, - DWORD flAllocationType, - DWORD flProtect -); - -WINDYNDEF WINDYN_EXPORT -INLINE BOOL WINAPI windyn_VirtualFreeEx( - HANDLE hProcess, - LPVOID lpAddress, - SIZE_T dwSize, - DWORD dwFreeType -); - -WINDYNDEF WINDYN_EXPORT -INLINE BOOL WINAPI windyn_VirtualProtectEx( - HANDLE hProcess, - LPVOID lpAddress, - SIZE_T dwSize, - DWORD flNewProtect, - PDWORD lpflOldProtect -); - -WINDYNDEF WINDYN_EXPORT -INLINE BOOL WINAPI windyn_CreateProcessA( - LPCSTR lpApplicationName, - LPSTR lpCommandLine, - LPSECURITY_ATTRIBUTES lpProcessAttributes, - LPSECURITY_ATTRIBUTES lpThreadAttributes, - BOOL bInheritHandles, - DWORD dwCreationFlags, - LPVOID lpEnvironment, - LPCSTR lpCurrentDirectory, - LPSTARTUPINFOA lpStartupInfo, - LPPROCESS_INFORMATION lpProcessInformation -); - -WINDYNDEF WINDYN_EXPORT -INLINE HANDLE WINAPI windyn_OpenProcess( - DWORD dwDesiredAccess, - BOOL bInheritHandle, - DWORD dwProcessId -); - -WINDYNDEF WINDYN_EXPORT -INLINE HANDLE WINAPI windyn_GetCurrentProcess( - VOID -); - -WINDYNDEF WINDYN_EXPORT -INLINE BOOL WINAPI windyn_ReadProcessMemory( - HANDLE hProcess, - LPCVOID lpBaseAddress, - LPVOID lpBuffer, - SIZE_T nSize, - SIZE_T* lpNumberOfBytesRead -); - -WINDYNDEF WINDYN_EXPORT -INLINE BOOL WINAPI windyn_WriteProcessMemory( - HANDLE hProcess, - LPVOID lpBaseAddress, - LPCVOID lpBuffer, - SIZE_T nSize, - SIZE_T* lpNumberOfBytesWritten -); - -WINDYNDEF WINDYN_EXPORT -INLINE HANDLE WINAPI windyn_CreateRemoteThread( - HANDLE hProcess, - LPSECURITY_ATTRIBUTES lpThreadAttributes, - SIZE_T dwStackSize, - LPTHREAD_START_ROUTINE lpStartAddress, - LPVOID lpParameter, - DWORD dwCreationFlags, - LPDWORD lpThreadId -); - -WINDYNDEF WINDYN_EXPORT -INLINE HANDLE WINAPI windyn_GetCurrentThread( - VOID -); - -WINDYNDEF WINDYN_EXPORT -INLINE DWORD WINAPI windyn_SuspendThread( - HANDLE hThread -); - -WINDYNDEF WINDYN_EXPORT -INLINE DWORD WINAPI windyn_ResumeThread( - HANDLE hThread -); - -WINDYNDEF WINDYN_EXPORT -INLINE BOOL WINAPI windyn_GetThreadContext( - HANDLE hThread, - LPCONTEXT lpContext -); - -WINDYNDEF WINDYN_EXPORT -INLINE BOOL WINAPI windyn_SetThreadContext( - HANDLE hThread, - CONST CONTEXT* lpContext -); - -WINDYNDEF WINDYN_EXPORT -INLINE DWORD WINAPI windyn_WaitForSingleObject( - HANDLE hHandle, - DWORD dwMilliseconds -); - -WINDYNDEF WINDYN_EXPORT -INLINE BOOL WINAPI windyn_CloseHandle( - HANDLE hObject -); - -WINDYNDEF WINDYN_EXPORT -INLINE HANDLE WINAPI windyn_CreateToolhelp32Snapshot( - DWORD dwFlags, - DWORD th32ProcessID -); - -WINDYNDEF WINDYN_EXPORT -INLINE BOOL WINAPI windyn_Process32First( - HANDLE hSnapshot, - LPPROCESSENTRY32 lppe -); - -WINDYNDEF WINDYN_EXPORT -INLINE BOOL WINAPI windyn_Process32Next( - HANDLE hSnapshot, - LPPROCESSENTRY32 lppe -); - -#ifdef WINDYN_IMPLEMENTATION -#include -#include -// util functions - -// stdc inline functions define -INLINE int windyn_strlen(const char* str1) -{ - const char* p = str1; - while (*p) p++; - return (int)(p - str1); -} - -WINDYNDEF WINDYN_EXPORT -INLINE int windyn_stricmp(const char* str1, const char* str2) -{ - int i = 0; - while (str1[i] != 0 && str2[i] != 0) - { - if (str1[i] == str2[i] - || str1[i] + 0x20 == str2[i] - || str2[i] + 0x20 == str1[i]) - { - i++; - } - else - { - return (int)str1[i] - (int)str2[i]; - } - } - return (int)str1[i] - (int)str2[i]; -} - -WINDYNDEF WINDYN_EXPORT -INLINE int windyn_stricmp2(const char* str1, const wchar_t* str2) -{ - int i = 0; - while (str1[i] != 0 && str2[i] != 0) - { - if ((wchar_t)str1[i] == str2[i] - || (wchar_t)str1[i] + 0x20 == str2[i] - || str2[i] + 0x20 == (wchar_t)str1[i]) - { - i++; - } - else - { - return (int)str1[i] - (int)str2[i]; - } - } - return (int)str1[i] - (int)str2[i]; -} - -WINDYNDEF WINDYN_EXPORT -INLINE int windyn_wcsicmp(const wchar_t * str1, const wchar_t* str2) -{ - int i = 0; - while (str1[i] != 0 && str2[i] != 0) - { - if (str1[i] == str2[i] - || str1[i] + 0x20 == str2[i] - || str2[i] + 0x20 == str1[i]) - { - i++; - } - else - { - return (int)str1[i] - (int)str2[i]; - } - } - return (int)str1[i] - (int)str2[i]; -} - -WINDYNDEF WINDYN_EXPORT -INLINE void* windyn_memset(void* buf, int ch, size_t n) -{ - char* p = buf; - for (size_t i = 0; i < n; i++) p[i] = (char)ch; - return buf; -} - -WINDYNDEF WINDYN_EXPORT -INLINE void* windyn_memcpy(void* dst, const void* src, size_t n) -{ - char* p1 = (char*)dst; - char* p2 = (char*)src; - for (size_t i = 0; i < n; i++) p1[i] = p2[i]; - return dst; -} - -// winapi inline functions define -WINDYNDEF WINDYN_EXPORT -INLINE HMODULE WINAPI windyn_GetModuleHandleA( - LPCSTR lpModuleName -) -{ - PPEB peb = NULL; - HMODULE hmod = NULL; - WINDYN_FINDMODULE(peb, lpModuleName, hmod); - return hmod; -} - -WINDYNDEF WINDYN_EXPORT -INLINE HMODULE WINAPI windyn_LoadLibraryA( - LPCSTR lpLibFileName -) -{ - HMODULE kernel32 = NULL; - WINDYN_FINDKERNEL32(kernel32); - PFN_LoadLibraryA pfnLoadLibraryA = NULL; - WINDYN_FINDLOADLIBRARYA(kernel32, pfnLoadLibraryA); - return pfnLoadLibraryA(lpLibFileName); -} - -WINDYNDEF WINDYN_EXPORT -INLINE FARPROC WINAPI windyn_GetProcAddress( - HMODULE hModule, - LPCSTR lpProcName -) -{ - HMODULE kernel32 = NULL; - WINDYN_FINDKERNEL32(kernel32); - PFN_GetProcAddress pfnGetProcAddress = NULL; - WINDYN_FINDGETPROCADDRESS(kernel32, pfnGetProcAddress); - return pfnGetProcAddress(hModule, lpProcName); -} - -WINDYNDEF WINDYN_EXPORT -INLINE LPVOID WINAPI windyn_VirtualAllocEx( - HANDLE hProcess, - LPVOID lpAddress, - SIZE_T dwSize, - DWORD flAllocationType, - DWORD flProtect -) -{ - HMODULE kernel32 = NULL; - WINDYN_FINDKERNEL32(kernel32); - PFN_GetProcAddress pfnGetProcAddress = NULL; - WINDYN_FINDGETPROCADDRESS(kernel32, pfnGetProcAddress); - - char name_VirtualAllocEx[] = { 'V', 'i', 'r', 't', 'u', 'a', 'l', 'A', 'l', 'l', 'o', 'c', 'E', 'x', '\0'}; - PFN_VirtualAllocEx pfnVirtualAllocEx = (PFN_VirtualAllocEx) - pfnGetProcAddress(kernel32, name_VirtualAllocEx); - return pfnVirtualAllocEx(hProcess, lpAddress, dwSize, flAllocationType, flProtect); -} - -WINDYNDEF WINDYN_EXPORT -INLINE BOOL WINAPI windyn_VirtualFreeEx( - HANDLE hProcess, - LPVOID lpAddress, - SIZE_T dwSize, - DWORD dwFreeType -); - -WINDYNDEF WINDYN_EXPORT -INLINE BOOL WINAPI windyn_VirtualProtectEx( - HANDLE hProcess, - LPVOID lpAddress, - SIZE_T dwSize, - DWORD flNewProtect, - PDWORD lpflOldProtect -); - -WINDYNDEF WINDYN_EXPORT -INLINE BOOL WINAPI windyn_CreateProcessA( - LPCSTR lpApplicationName, - LPSTR lpCommandLine, - LPSECURITY_ATTRIBUTES lpProcessAttributes, - LPSECURITY_ATTRIBUTES lpThreadAttributes, - BOOL bInheritHandles, - DWORD dwCreationFlags, - LPVOID lpEnvironment, - LPCSTR lpCurrentDirectory, - LPSTARTUPINFOA lpStartupInfo, - LPPROCESS_INFORMATION lpProcessInformation -); - -WINDYNDEF WINDYN_EXPORT -INLINE HANDLE WINAPI windyn_OpenProcess( - DWORD dwDesiredAccess, - BOOL bInheritHandle, - DWORD dwProcessId -); - -WINDYNDEF WINDYN_EXPORT -INLINE HANDLE WINAPI windyn_GetCurrentProcess( - VOID -); - -WINDYNDEF WINDYN_EXPORT -INLINE BOOL WINAPI windyn_ReadProcessMemory( - HANDLE hProcess, - LPCVOID lpBaseAddress, - LPVOID lpBuffer, - SIZE_T nSize, - SIZE_T* lpNumberOfBytesRead -); - -WINDYNDEF WINDYN_EXPORT -INLINE BOOL WINAPI windyn_WriteProcessMemory( - HANDLE hProcess, - LPVOID lpBaseAddress, - LPCVOID lpBuffer, - SIZE_T nSize, - SIZE_T* lpNumberOfBytesWritten -); - -WINDYNDEF WINDYN_EXPORT -INLINE HANDLE WINAPI windyn_CreateRemoteThread( - HANDLE hProcess, - LPSECURITY_ATTRIBUTES lpThreadAttributes, - SIZE_T dwStackSize, - LPTHREAD_START_ROUTINE lpStartAddress, - LPVOID lpParameter, - DWORD dwCreationFlags, - LPDWORD lpThreadId -); - -WINDYNDEF WINDYN_EXPORT -INLINE HANDLE WINAPI windyn_GetCurrentThread( - VOID -); - -WINDYNDEF WINDYN_EXPORT -INLINE DWORD WINAPI windyn_SuspendThread( - HANDLE hThread -); - -WINDYNDEF WINDYN_EXPORT -INLINE DWORD WINAPI windyn_ResumeThread( - HANDLE hThread -); - -WINDYNDEF WINDYN_EXPORT -INLINE BOOL WINAPI windyn_GetThreadContext( - HANDLE hThread, - LPCONTEXT lpContext -); - -WINDYNDEF WINDYN_EXPORT -INLINE BOOL WINAPI windyn_SetThreadContext( - HANDLE hThread, - CONST CONTEXT* lpContext -); - -WINDYNDEF WINDYN_EXPORT -INLINE DWORD WINAPI windyn_WaitForSingleObject( - HANDLE hHandle, - DWORD dwMilliseconds -); - -WINDYNDEF WINDYN_EXPORT -INLINE BOOL WINAPI windyn_CloseHandle( - HANDLE hObject -); - -WINDYNDEF WINDYN_EXPORT -INLINE HANDLE WINAPI windyn_CreateToolhelp32Snapshot( - DWORD dwFlags, - DWORD th32ProcessID -); - -WINDYNDEF WINDYN_EXPORT -INLINE BOOL WINAPI windyn_Process32First( - HANDLE hSnapshot, - LPPROCESSENTRY32 lppe -); - -WINDYNDEF WINDYN_EXPORT -INLINE BOOL WINAPI windyn_Process32Next( - HANDLE hSnapshot, - LPPROCESSENTRY32 lppe -); - -#endif - -#ifdef __cplusplus -} -#endif - -#endif - -/* -* history -* v0.1, initial version -* v0.1.1, add some function pointer -* v0.1.2, add some inline stdc function -* v0.1.3, add some inline windows api +/* +windows api function pointer define, +functions or macros for dynamic bindings + v0.1.3, developed by devseed +*/ + +#ifndef _WINDYN_H +#define _WINDYN_H +#define WINDYN_VERSION 130 + +#include +#include +#include + +#ifndef WINDYNDEF +#ifdef WINDYN_STATIC +#define WINDYNDEF static +#else +#define WINDYNDEF extern +#endif +#endif + +#ifndef WINDYN_SHARED +#define WINDYN_EXPORT +#else +#ifdef _WIN32 +#define WINDYN_EXPORT __declspec(dllexport) +#else +#define WINDYN_EXPORT __attribute__((visibility("default"))) +#endif +#endif + +#ifndef INLINE +#if defined(_MSC_VER) +#define INLINE __forceinline +#else // tcc, gcc not support inline export ... +#define INLINE +#endif +#endif + +#ifdef __cplusplus +extern "C" { +#endif + +// function pointer declear +typedef HMODULE (WINAPI* PFN_LoadLibraryA)( + LPCSTR lpLibFileName +); + +typedef FARPROC (WINAPI* PFN_GetProcAddress)( + HMODULE hModule, + LPCSTR lpProcName +); + +typedef HMODULE (WINAPI *PFN_GetModuleHandleA)( + LPCSTR lpModuleName +); + +typedef LPVOID (WINAPI *PFN_VirtualAllocEx)( + HANDLE hProcess, + LPVOID lpAddress, + SIZE_T dwSize, + DWORD flAllocationType, + DWORD flProtect +); + +typedef BOOL (WINAPI *PFN_VirtualFreeEx)( + HANDLE hProcess, + LPVOID lpAddress, + SIZE_T dwSize, + DWORD dwFreeType +); + +typedef BOOL (WINAPI *PFN_VirtualProtectEx)( + HANDLE hProcess, + LPVOID lpAddress, + SIZE_T dwSize, + DWORD flNewProtect, + PDWORD lpflOldProtect +); + +typedef BOOL (WINAPI *PFN_CreateProcessA)( + LPCSTR lpApplicationName, + LPSTR lpCommandLine, + LPSECURITY_ATTRIBUTES lpProcessAttributes, + LPSECURITY_ATTRIBUTES lpThreadAttributes, + BOOL bInheritHandles, + DWORD dwCreationFlags, + LPVOID lpEnvironment, + LPCSTR lpCurrentDirectory, + LPSTARTUPINFOA lpStartupInfo, + LPPROCESS_INFORMATION lpProcessInformation +); + +typedef HANDLE (WINAPI *PFN_OpenProcess)( + DWORD dwDesiredAccess, + BOOL bInheritHandle, + DWORD dwProcessId +); + +typedef HANDLE (WINAPI *PFN_GetCurrentProcess)( + VOID +); + +typedef BOOL (WINAPI *PFN_ReadProcessMemory)( + HANDLE hProcess, + LPCVOID lpBaseAddress, + LPVOID lpBuffer, + SIZE_T nSize, + SIZE_T* lpNumberOfBytesRead +); + +typedef BOOL (WINAPI *PFN_WriteProcessMemory)( + HANDLE hProcess, + LPVOID lpBaseAddress, + LPCVOID lpBuffer, + SIZE_T nSize, + SIZE_T* lpNumberOfBytesWritten +); + +typedef HANDLE (WINAPI *PFN_CreateRemoteThread)( + HANDLE hProcess, + LPSECURITY_ATTRIBUTES lpThreadAttributes, + SIZE_T dwStackSize, + LPTHREAD_START_ROUTINE lpStartAddress, + LPVOID lpParameter, + DWORD dwCreationFlags, + LPDWORD lpThreadId +); + +typedef HANDLE (WINAPI *PFN_GetCurrentThread)( + VOID +); + +typedef DWORD (WINAPI *PFN_SuspendThread)( + HANDLE hThread +); + +typedef DWORD (WINAPI *PFN_ResumeThread)( + HANDLE hThread +); + +typedef BOOL (WINAPI *PFN_GetThreadContext)( + HANDLE hThread, + LPCONTEXT lpContext +); + +typedef BOOL (WINAPI *PFN_SetThreadContext)( + HANDLE hThread, + CONST CONTEXT* lpContext +); + +typedef DWORD (WINAPI *PFN_WaitForSingleObject)( + HANDLE hHandle, + DWORD dwMilliseconds +); + +typedef BOOL (WINAPI *PFN_CloseHandle)( + HANDLE hObject +); + +typedef HANDLE (WINAPI *PFN_CreateToolhelp32Snapshot)( + DWORD dwFlags, + DWORD th32ProcessID +); + +typedef BOOL (WINAPI *PFN_Process32First)( + HANDLE hSnapshot, + LPPROCESSENTRY32 lppe +); + +typedef BOOL (WINAPI *PFN_Process32Next)( + HANDLE hSnapshot, + LPPROCESSENTRY32 lppe +); + +typedef NTSTATUS (NTAPI * PFN_NtQueryInformationProcess)( + IN HANDLE ProcessHandle, + IN PROCESSINFOCLASS ProcessInformationClass, + OUT PVOID ProcessInformation, + IN ULONG ProcessInformationLength, + OUT PULONG ReturnLength +); + +// util inline functions and macro declear +#define WINDYN_FINDEXP(mempe, funcname, exp)\ +{\ + PIMAGE_DOS_HEADER pDosHeader = (PIMAGE_DOS_HEADER)mempe;\ + PIMAGE_NT_HEADERS pNtHeader = (PIMAGE_NT_HEADERS)\ + ((uint8_t*)mempe + pDosHeader->e_lfanew);\ + PIMAGE_FILE_HEADER pFileHeader = &pNtHeader->FileHeader;\ + PIMAGE_OPTIONAL_HEADER pOptHeader = &pNtHeader->OptionalHeader;\ + PIMAGE_DATA_DIRECTORY pDataDirectory = pOptHeader->DataDirectory;\ + PIMAGE_DATA_DIRECTORY pExpEntry =\ + &pDataDirectory[IMAGE_DIRECTORY_ENTRY_EXPORT];\ + PIMAGE_EXPORT_DIRECTORY pExpDescriptor =\ + (PIMAGE_EXPORT_DIRECTORY)((uint8_t*)mempe + pExpEntry->VirtualAddress);\ + WORD* ordrva = (WORD*)((uint8_t*)mempe\ + + pExpDescriptor->AddressOfNameOrdinals);\ + DWORD* namerva = (DWORD*)((uint8_t*)mempe\ + + pExpDescriptor->AddressOfNames);\ + DWORD* funcrva = (DWORD*)((uint8_t*)mempe\ + + pExpDescriptor->AddressOfFunctions);\ + if ((size_t)funcname <= MAXWORD)\ + {\ + WORD ordbase = LOWORD(pExpDescriptor->Base) - 1;\ + WORD funcord = LOWORD(funcname);\ + exp = (void*)((uint8_t*)mempe + funcrva[ordrva[funcord - ordbase]]);\ + }\ + else\ + {\ + for (DWORD i = 0; i < pExpDescriptor->NumberOfNames; i++)\ + {\ + LPCSTR curname = (LPCSTR)((uint8_t*)mempe + namerva[i]);\ + if (windyn_stricmp(curname, funcname) == 0)\ + {\ + exp = (void*)((uint8_t*)mempe + funcrva[ordrva[i]]); \ + break;\ + }\ + }\ + }\ +} + +#define WINDYN_FINDMODULE(peb, modulename, hmod)\ +{\ + typedef struct _LDR_ENTRY \ + {\ + LIST_ENTRY InLoadOrderLinks; \ + LIST_ENTRY InMemoryOrderLinks;\ + LIST_ENTRY InInitializationOrderLinks;\ + PVOID DllBase;\ + PVOID EntryPoint;\ + ULONG SizeOfImage;\ + UNICODE_STRING FullDllName;\ + UNICODE_STRING BaseDllName;\ + ULONG Flags;\ + USHORT LoadCount;\ + USHORT TlsIndex;\ + union\ + {\ + LIST_ENTRY HashLinks;\ + struct\ + {\ + PVOID SectionPointer;\ + ULONG CheckSum;\ + };\ + };\ + ULONG TimeDateStamp;\ + } LDR_ENTRY, * PLDR_ENTRY; \ + PLDR_ENTRY ldrentry = NULL;\ + PPEB_LDR_DATA ldr = NULL;\ + if (!peb)\ + {\ + PTEB teb = NtCurrentTeb();\ + if(sizeof(size_t)>4) peb = *(PPEB*)((uint8_t*)teb + 0x60);\ + else peb = *(PPEB*)((uint8_t*)teb + 0x30);\ + }\ + if(sizeof(size_t)>4) ldr = *(PPEB_LDR_DATA*)((uint8_t*)peb + 0x18);\ + else ldr = *(PPEB_LDR_DATA*)((uint8_t*)peb + 0xC);\ + ldrentry = (PLDR_ENTRY)((size_t)\ + ldr->InMemoryOrderModuleList.Flink - 2 * sizeof(size_t));\ + if (!modulename)\ + {\ + hmod = ldrentry->DllBase;\ + }\ + else\ + {\ + while (ldrentry->InMemoryOrderLinks.Flink != \ + ldr->InMemoryOrderModuleList.Flink)\ + {\ + PUNICODE_STRING ustr = &ldrentry->FullDllName; \ + int i; \ + for (i = ustr->Length / 2 - 1; i > 0 && ustr->Buffer[i] != '\\'; i--); \ + if (ustr->Buffer[i] == '\\') i++; \ + if (windyn_stricmp2(modulename, ustr->Buffer + i) == 0)\ + {\ + hmod = ldrentry->DllBase; \ + break; \ + }\ + ldrentry = (PLDR_ENTRY)((size_t)\ + ldrentry->InMemoryOrderLinks.Flink - 2 * sizeof(size_t)); \ + }\ + }\ +} + +#define WINDYN_FINDKERNEL32(kernel32)\ +{\ + PPEB peb = NULL;\ + char name_kernel32[] = { 'k', 'e', 'r', 'n', 'e', 'l', '3', '2', '.', 'd', 'l', 'l', '\0' }; \ + WINDYN_FINDMODULE(peb, name_kernel32, kernel32);\ +} + +#define WINDYN_FINDLOADLIBRARYA(kernel32, pfnLoadLibraryA)\ +{\ + char name_LoadLibraryA[] = { 'L', 'o', 'a', 'd', 'L', 'i', 'b', 'r', 'a', 'r', 'y', 'A', '\0' };\ + WINDYN_FINDEXP((void*)kernel32, name_LoadLibraryA, pfnLoadLibraryA);\ +}\ + +#define WINDYN_FINDGETPROCADDRESS(kernel32, pfnGetProcAddress)\ +{\ + char name_GetProcAddress[] = { 'G', 'e', 't', 'P', 'r', 'o', 'c', 'A', 'd', 'd', 'r', 'e', 's', 's', '\0' }; \ + WINDYN_FINDEXP((void*)kernel32, name_GetProcAddress, pfnGetProcAddress);\ +} + +// stdc inline functions declear +WINDYNDEF WINDYN_EXPORT +int windyn_strlen(const char* str1); + +WINDYNDEF WINDYN_EXPORT +int windyn_stricmp(const char* str1, const char* str2); + +WINDYNDEF WINDYN_EXPORT +INLINE int windyn_stricmp2(const char* str1, const wchar_t* str2); + +WINDYNDEF WINDYN_EXPORT +INLINE int windyn_wcsicmp(const wchar_t* str1, const wchar_t* str2); + +WINDYNDEF WINDYN_EXPORT +INLINE void* windyn_memset(void* buf, int ch, size_t n); + +WINDYNDEF WINDYN_EXPORT +INLINE void* windyn_memcpy(void* dst, const void* src, size_t n); + +// winapi inline functions declear +WINDYNDEF WINDYN_EXPORT +INLINE HMODULE WINAPI windyn_GetModuleHandleA( + LPCSTR lpModuleName +); + +WINDYNDEF WINDYN_EXPORT +INLINE HMODULE WINAPI windyn_LoadLibraryA( + LPCSTR lpLibFileName +); + +WINDYNDEF WINDYN_EXPORT +INLINE FARPROC WINAPI windyn_GetProcAddress( + HMODULE hModule, + LPCSTR lpProcName +); + +WINDYNDEF WINDYN_EXPORT +INLINE LPVOID WINAPI windyn_VirtualAllocEx( + HANDLE hProcess, + LPVOID lpAddress, + SIZE_T dwSize, + DWORD flAllocationType, + DWORD flProtect +); + +WINDYNDEF WINDYN_EXPORT +INLINE BOOL WINAPI windyn_VirtualFreeEx( + HANDLE hProcess, + LPVOID lpAddress, + SIZE_T dwSize, + DWORD dwFreeType +); + +WINDYNDEF WINDYN_EXPORT +INLINE BOOL WINAPI windyn_VirtualProtectEx( + HANDLE hProcess, + LPVOID lpAddress, + SIZE_T dwSize, + DWORD flNewProtect, + PDWORD lpflOldProtect +); + +WINDYNDEF WINDYN_EXPORT +INLINE BOOL WINAPI windyn_CreateProcessA( + LPCSTR lpApplicationName, + LPSTR lpCommandLine, + LPSECURITY_ATTRIBUTES lpProcessAttributes, + LPSECURITY_ATTRIBUTES lpThreadAttributes, + BOOL bInheritHandles, + DWORD dwCreationFlags, + LPVOID lpEnvironment, + LPCSTR lpCurrentDirectory, + LPSTARTUPINFOA lpStartupInfo, + LPPROCESS_INFORMATION lpProcessInformation +); + +WINDYNDEF WINDYN_EXPORT +INLINE HANDLE WINAPI windyn_OpenProcess( + DWORD dwDesiredAccess, + BOOL bInheritHandle, + DWORD dwProcessId +); + +WINDYNDEF WINDYN_EXPORT +INLINE HANDLE WINAPI windyn_GetCurrentProcess( + VOID +); + +WINDYNDEF WINDYN_EXPORT +INLINE BOOL WINAPI windyn_ReadProcessMemory( + HANDLE hProcess, + LPCVOID lpBaseAddress, + LPVOID lpBuffer, + SIZE_T nSize, + SIZE_T* lpNumberOfBytesRead +); + +WINDYNDEF WINDYN_EXPORT +INLINE BOOL WINAPI windyn_WriteProcessMemory( + HANDLE hProcess, + LPVOID lpBaseAddress, + LPCVOID lpBuffer, + SIZE_T nSize, + SIZE_T* lpNumberOfBytesWritten +); + +WINDYNDEF WINDYN_EXPORT +INLINE HANDLE WINAPI windyn_CreateRemoteThread( + HANDLE hProcess, + LPSECURITY_ATTRIBUTES lpThreadAttributes, + SIZE_T dwStackSize, + LPTHREAD_START_ROUTINE lpStartAddress, + LPVOID lpParameter, + DWORD dwCreationFlags, + LPDWORD lpThreadId +); + +WINDYNDEF WINDYN_EXPORT +INLINE HANDLE WINAPI windyn_GetCurrentThread( + VOID +); + +WINDYNDEF WINDYN_EXPORT +INLINE DWORD WINAPI windyn_SuspendThread( + HANDLE hThread +); + +WINDYNDEF WINDYN_EXPORT +INLINE DWORD WINAPI windyn_ResumeThread( + HANDLE hThread +); + +WINDYNDEF WINDYN_EXPORT +INLINE BOOL WINAPI windyn_GetThreadContext( + HANDLE hThread, + LPCONTEXT lpContext +); + +WINDYNDEF WINDYN_EXPORT +INLINE BOOL WINAPI windyn_SetThreadContext( + HANDLE hThread, + CONST CONTEXT* lpContext +); + +WINDYNDEF WINDYN_EXPORT +INLINE DWORD WINAPI windyn_WaitForSingleObject( + HANDLE hHandle, + DWORD dwMilliseconds +); + +WINDYNDEF WINDYN_EXPORT +INLINE BOOL WINAPI windyn_CloseHandle( + HANDLE hObject +); + +WINDYNDEF WINDYN_EXPORT +INLINE HANDLE WINAPI windyn_CreateToolhelp32Snapshot( + DWORD dwFlags, + DWORD th32ProcessID +); + +WINDYNDEF WINDYN_EXPORT +INLINE BOOL WINAPI windyn_Process32First( + HANDLE hSnapshot, + LPPROCESSENTRY32 lppe +); + +WINDYNDEF WINDYN_EXPORT +INLINE BOOL WINAPI windyn_Process32Next( + HANDLE hSnapshot, + LPPROCESSENTRY32 lppe +); + +#ifdef WINDYN_IMPLEMENTATION +#include +#include +// util functions + +// stdc inline functions define +INLINE int windyn_strlen(const char* str1) +{ + const char* p = str1; + while (*p) p++; + return (int)(p - str1); +} + +WINDYNDEF WINDYN_EXPORT +INLINE int windyn_stricmp(const char* str1, const char* str2) +{ + int i = 0; + while (str1[i] != 0 && str2[i] != 0) + { + if (str1[i] == str2[i] + || str1[i] + 0x20 == str2[i] + || str2[i] + 0x20 == str1[i]) + { + i++; + } + else + { + return (int)str1[i] - (int)str2[i]; + } + } + return (int)str1[i] - (int)str2[i]; +} + +WINDYNDEF WINDYN_EXPORT +INLINE int windyn_stricmp2(const char* str1, const wchar_t* str2) +{ + int i = 0; + while (str1[i] != 0 && str2[i] != 0) + { + if ((wchar_t)str1[i] == str2[i] + || (wchar_t)str1[i] + 0x20 == str2[i] + || str2[i] + 0x20 == (wchar_t)str1[i]) + { + i++; + } + else + { + return (int)str1[i] - (int)str2[i]; + } + } + return (int)str1[i] - (int)str2[i]; +} + +WINDYNDEF WINDYN_EXPORT +INLINE int windyn_wcsicmp(const wchar_t * str1, const wchar_t* str2) +{ + int i = 0; + while (str1[i] != 0 && str2[i] != 0) + { + if (str1[i] == str2[i] + || str1[i] + 0x20 == str2[i] + || str2[i] + 0x20 == str1[i]) + { + i++; + } + else + { + return (int)str1[i] - (int)str2[i]; + } + } + return (int)str1[i] - (int)str2[i]; +} + +WINDYNDEF WINDYN_EXPORT +INLINE void* windyn_memset(void* buf, int ch, size_t n) +{ + char* p = buf; + for (size_t i = 0; i < n; i++) p[i] = (char)ch; + return buf; +} + +WINDYNDEF WINDYN_EXPORT +INLINE void* windyn_memcpy(void* dst, const void* src, size_t n) +{ + char* p1 = (char*)dst; + char* p2 = (char*)src; + for (size_t i = 0; i < n; i++) p1[i] = p2[i]; + return dst; +} + +// winapi inline functions define +WINDYNDEF WINDYN_EXPORT +INLINE HMODULE WINAPI windyn_GetModuleHandleA( + LPCSTR lpModuleName +) +{ + PPEB peb = NULL; + HMODULE hmod = NULL; + WINDYN_FINDMODULE(peb, lpModuleName, hmod); + return hmod; +} + +WINDYNDEF WINDYN_EXPORT +INLINE HMODULE WINAPI windyn_LoadLibraryA( + LPCSTR lpLibFileName +) +{ + HMODULE kernel32 = NULL; + WINDYN_FINDKERNEL32(kernel32); + PFN_LoadLibraryA pfnLoadLibraryA = NULL; + WINDYN_FINDLOADLIBRARYA(kernel32, pfnLoadLibraryA); + return pfnLoadLibraryA(lpLibFileName); +} + +WINDYNDEF WINDYN_EXPORT +INLINE FARPROC WINAPI windyn_GetProcAddress( + HMODULE hModule, + LPCSTR lpProcName +) +{ + HMODULE kernel32 = NULL; + WINDYN_FINDKERNEL32(kernel32); + PFN_GetProcAddress pfnGetProcAddress = NULL; + WINDYN_FINDGETPROCADDRESS(kernel32, pfnGetProcAddress); + return pfnGetProcAddress(hModule, lpProcName); +} + +WINDYNDEF WINDYN_EXPORT +INLINE LPVOID WINAPI windyn_VirtualAllocEx( + HANDLE hProcess, + LPVOID lpAddress, + SIZE_T dwSize, + DWORD flAllocationType, + DWORD flProtect +) +{ + HMODULE kernel32 = NULL; + WINDYN_FINDKERNEL32(kernel32); + PFN_GetProcAddress pfnGetProcAddress = NULL; + WINDYN_FINDGETPROCADDRESS(kernel32, pfnGetProcAddress); + + char name_VirtualAllocEx[] = { 'V', 'i', 'r', 't', 'u', 'a', 'l', 'A', 'l', 'l', 'o', 'c', 'E', 'x', '\0'}; + PFN_VirtualAllocEx pfnVirtualAllocEx = (PFN_VirtualAllocEx) + pfnGetProcAddress(kernel32, name_VirtualAllocEx); + return pfnVirtualAllocEx(hProcess, lpAddress, dwSize, flAllocationType, flProtect); +} + +WINDYNDEF WINDYN_EXPORT +INLINE BOOL WINAPI windyn_VirtualFreeEx( + HANDLE hProcess, + LPVOID lpAddress, + SIZE_T dwSize, + DWORD dwFreeType +); + +WINDYNDEF WINDYN_EXPORT +INLINE BOOL WINAPI windyn_VirtualProtectEx( + HANDLE hProcess, + LPVOID lpAddress, + SIZE_T dwSize, + DWORD flNewProtect, + PDWORD lpflOldProtect +); + +WINDYNDEF WINDYN_EXPORT +INLINE BOOL WINAPI windyn_CreateProcessA( + LPCSTR lpApplicationName, + LPSTR lpCommandLine, + LPSECURITY_ATTRIBUTES lpProcessAttributes, + LPSECURITY_ATTRIBUTES lpThreadAttributes, + BOOL bInheritHandles, + DWORD dwCreationFlags, + LPVOID lpEnvironment, + LPCSTR lpCurrentDirectory, + LPSTARTUPINFOA lpStartupInfo, + LPPROCESS_INFORMATION lpProcessInformation +); + +WINDYNDEF WINDYN_EXPORT +INLINE HANDLE WINAPI windyn_OpenProcess( + DWORD dwDesiredAccess, + BOOL bInheritHandle, + DWORD dwProcessId +); + +WINDYNDEF WINDYN_EXPORT +INLINE HANDLE WINAPI windyn_GetCurrentProcess( + VOID +); + +WINDYNDEF WINDYN_EXPORT +INLINE BOOL WINAPI windyn_ReadProcessMemory( + HANDLE hProcess, + LPCVOID lpBaseAddress, + LPVOID lpBuffer, + SIZE_T nSize, + SIZE_T* lpNumberOfBytesRead +); + +WINDYNDEF WINDYN_EXPORT +INLINE BOOL WINAPI windyn_WriteProcessMemory( + HANDLE hProcess, + LPVOID lpBaseAddress, + LPCVOID lpBuffer, + SIZE_T nSize, + SIZE_T* lpNumberOfBytesWritten +); + +WINDYNDEF WINDYN_EXPORT +INLINE HANDLE WINAPI windyn_CreateRemoteThread( + HANDLE hProcess, + LPSECURITY_ATTRIBUTES lpThreadAttributes, + SIZE_T dwStackSize, + LPTHREAD_START_ROUTINE lpStartAddress, + LPVOID lpParameter, + DWORD dwCreationFlags, + LPDWORD lpThreadId +); + +WINDYNDEF WINDYN_EXPORT +INLINE HANDLE WINAPI windyn_GetCurrentThread( + VOID +); + +WINDYNDEF WINDYN_EXPORT +INLINE DWORD WINAPI windyn_SuspendThread( + HANDLE hThread +); + +WINDYNDEF WINDYN_EXPORT +INLINE DWORD WINAPI windyn_ResumeThread( + HANDLE hThread +); + +WINDYNDEF WINDYN_EXPORT +INLINE BOOL WINAPI windyn_GetThreadContext( + HANDLE hThread, + LPCONTEXT lpContext +); + +WINDYNDEF WINDYN_EXPORT +INLINE BOOL WINAPI windyn_SetThreadContext( + HANDLE hThread, + CONST CONTEXT* lpContext +); + +WINDYNDEF WINDYN_EXPORT +INLINE DWORD WINAPI windyn_WaitForSingleObject( + HANDLE hHandle, + DWORD dwMilliseconds +); + +WINDYNDEF WINDYN_EXPORT +INLINE BOOL WINAPI windyn_CloseHandle( + HANDLE hObject +); + +WINDYNDEF WINDYN_EXPORT +INLINE HANDLE WINAPI windyn_CreateToolhelp32Snapshot( + DWORD dwFlags, + DWORD th32ProcessID +); + +WINDYNDEF WINDYN_EXPORT +INLINE BOOL WINAPI windyn_Process32First( + HANDLE hSnapshot, + LPPROCESSENTRY32 lppe +); + +WINDYNDEF WINDYN_EXPORT +INLINE BOOL WINAPI windyn_Process32Next( + HANDLE hSnapshot, + LPPROCESSENTRY32 lppe +); + +#endif + +#ifdef __cplusplus +} +#endif + +#endif + +/* +* history +* v0.1, initial version +* v0.1.1, add some function pointer +* v0.1.2, add some inline stdc function +* v0.1.3, add some inline windows api */ \ No newline at end of file diff --git a/include/winhook.h b/src/c/include/winhook.h similarity index 96% rename from include/winhook.h rename to src/c/include/winhook.h index e8d2850..5360f87 100644 --- a/include/winhook.h +++ b/src/c/include/winhook.h @@ -1,774 +1,781 @@ -/** - * windows dyamic hook util functions wrappers - * v0.3.1, developed by devseed -*/ - -#ifndef _WINHOOK_H -#define _WINHOOK_H -#include - -#ifndef WINHOOKDEF -#ifdef WINHOOK_STATIC -#define WINHOOKDEF static -#else -#define WINHOOKDEF extern -#endif -#endif - -#ifndef WINHOOK_SHARED -#define WINHOOK_EXPORT -#else -#ifdef _WIN32 -#define WINHOOK_EXPORT __declspec(dllexport) -#else -#define WINHOOK_EXPORT __attribute__((visibility("default"))) -#endif -#endif - -#ifndef INLINE -#ifdef WINHOOK_USESHELLCODE -#if defined(_MSC_VER) -#define INLINE __forceinline -#else // tcc, gcc not support inline export ... -#define INLINE -#endif -#else -#define INLINE -#endif -#endif - -#ifdef __cplusplus -extern "C" { -#endif -// loader functions -/** - * start a exe and inject dll into exe - * return pid -*/ -WINHOOKDEF WINHOOK_EXPORT -INLINE DWORD winhook_startexeinject(LPCSTR exepath, - LPSTR cmdstr, LPCSTR dllpath); - -/** - * start a exe by CreateProcess - * @return pid -*/ -#define winhook_startexe(exepath, cmdstr)\ - winhook_startexeinject(exepath, cmdstr, NULL) - - -/** - * get the process handle by exename -*/ -WINHOOKDEF WINHOOK_EXPORT -INLINE HANDLE winhook_getprocess(LPCWSTR exename); - -/** - * get the other process image base -*/ -WINHOOKDEF WINHOOK_EXPORT -INLINE size_t winhook_getimagebase(HANDLE hprocess); - -/** - * dynamic inject a dll into a process -*/ -WINHOOKDEF WINHOOK_EXPORT -INLINE BOOL winhook_injectdll(HANDLE hprocess, LPCSTR dllname); - -/** - * alloc a console for the program -*/ -WINHOOKDEF WINHOOK_EXPORT -INLINE void winhook_installconsole(); - - -// dynamic hook functions -/** - * patch addr by buf with bufsize -*/ -WINHOOKDEF WINHOOK_EXPORT -INLINE BOOL winhook_patchmemoryex(HANDLE hprocess, - LPVOID addr, const void* buf, size_t bufsize); - -#define winhook_patchmemory(addr, buf, bufsize)\ - winhook_patchmemoryex(GetCurrentProcess(), addr, buf, bufsize) - -/** - * batch patch memories -*/ -WINHOOKDEF WINHOOK_EXPORT -INLINE BOOL winhook_patchmemorysex(HANDLE hprocess, - LPVOID addrs[], void* bufs[], - size_t bufsizes[], int n); - -#define winhook_patchmemorys(addrs, bufs, bufsizes, n)\ - winhook_patchmemorysex(GetCurrentProcess(), addrs, bufs, bufsizes, n) - -/** - * patch memory with pattern, - * @param pattern - * skip '#' line, + for reative address, then multi byte code (hex) - * 00400000: ff 90 - * +3f00: 90 90 90 90 - * +3f06: 90; +3f08: 90 - * @return patch bytes number, error < 0 -*/ -WINHOOKDEF WINHOOK_EXPORT -INLINE int winhook_patchmemorypattern(const char *pattern); - -/** - * patch memory with pattern 1337 by x64dbg, use rva - * can use ';' instead of '\r' '\n' -*/ -WINHOOKDEF WINHOOK_EXPORT -INLINE int winhook_patchmemory1337ex(HANDLE hprocess, const char* pattern, size_t base, BOOL revert); - -#define winhook_patchmemory1337(pattern, base, revert) \ - winhook_patchmemory1337ex(GetCurrentProcess(), pattern, base, revert) - -/** - * patch memory with pattern ips(International Patching System) - * specifications at https://zerosoft.zophar.net/ips.php - * addr is relative to base, big endian -*/ -WINHOOKDEF WINHOOK_EXPORT -INLINE int winhook_patchmemoryipsex(HANDLE hprocess, const char* pattern, size_t base); - -#define winhook_patchmemoryips(pattern, base) \ - winhook_patchmemoryipsex(GetCurrentProcess(), pattern, base) - -/** - * search the pattern like "ab 12 ?? 34" - * @return the matched address -*/ -WINHOOKDEF WINHOOK_EXPORT -INLINE void* winhook_searchmemory(void* addr, size_t memsize, - const char* pattern, size_t *pmatchsize); - -WINHOOKDEF WINHOOK_EXPORT -INLINE void* winhook_searchmemoryex(HANDLE hprocess, - void* addr, size_t memsize, - const char* pattern, size_t* pmatchsize); - -/** - * winhook_iathookmodule is for windows dll, - * @param moduleDllName is which dll to hook iat -*/ -WINHOOKDEF WINHOOK_EXPORT -INLINE BOOL winhook_iathookpe(LPCSTR targetDllName, - void* mempe, PROC pfnOrg, PROC pfnNew); - -#define winhook_iathookmodule(targetDllName, moduleDllName, pfnOrg, pfnNew)\ - winhook_iathookpe(targetDllName, GetModuleHandle(moduleDllName), pfnOrg, pfnNew) - -/** - * iat dynamiclly hook, - * replace the @param pfgNew with @param pfnOrg function - * @param targetDllName like "user32.dll", "kernel32.dll" -*/ -#define winhook_iathook(targetDllName, pfnOrg, pfgNew)\ - winhook_iathookmodule(targetDllName, NULL, pfnOrg, pfgNew) - -/** - * inline hooks wrapper, - * @param pfnTargets -> @param pfnNews, save origin pointers in @param pfnOlds - * @return: success hook numbers -*/ -WINHOOKDEF WINHOOK_EXPORT -int winhook_inlinehooks(PVOID pfnTargets[], - PVOID pfnNews[], PVOID pfnOlds[], size_t n); - -WINHOOKDEF WINHOOK_EXPORT -int winhook_inlineunhooks(PVOID pfnTargets[], - PVOID pfnNews[], PVOID pfnOlds[], size_t n); - -#endif - -#ifdef __cplusplus -} -#endif - -#ifdef WINHOOK_IMPLEMENTATION -#include -#include -#include -#include -#include -#include - -#ifdef WINHOOK_USESHELLCODE -#define WINDYN_IMPLEMENTATION -#define WINDYN_STATIC -#include "windyn.h" -#define strlen windyn_strlen -#define _stricmp windyn_stricmp -#define _wcsicmp windyn_wcsicmp -#define GetModuleHandleA windyn_GetModuleHandleA -#define LoadLibraryA windyn_LoadLibraryA -#define GetProcAddress windyn_GetProcAddress -#define VirtualAllocEx windyn_VirtualAllocEx -#endif - -// loader functions -WINHOOKDEF WINHOOK_EXPORT -INLINE DWORD winhook_startexeinject(LPCSTR exepath, - LPSTR cmdstr, LPCSTR dllpath) -{ - STARTUPINFOA si = {0}; - PROCESS_INFORMATION pi = {0}; - si.cb = sizeof(STARTUPINFOA); - if (!CreateProcessA(exepath, cmdstr, - NULL, NULL, FALSE, CREATE_SUSPENDED, NULL, NULL, &si, &pi)) - return 0; - - if (dllpath) // inject dll to process - { - size_t n = 0; - HANDLE hprocess = pi.hProcess; - HANDLE hthread = pi.hThread; - LPVOID injectaddr = VirtualAllocEx(hprocess, - 0, 0x1000, MEM_COMMIT, PAGE_EXECUTE_READWRITE); - size_t oepva = 0; - - // prepare shellcode - CONTEXT context = { 0 }; - context.ContextFlags = CONTEXT_ALL; - GetThreadContext(hthread, &context); -#ifdef _WIN64 - uint8_t injectcode[] = {0x50,0x53,0x51,0x52,0xe8,0x2d,0x00,0x00,0x00,0x48,0x8d,0x58,0xf7,0x48,0x83,0xec,0x28,0x48,0x8b,0x8b,0x43,0x00,0x00,0x00,0x48,0x8b,0x83,0x4b,0x00,0x00,0x00,0xff,0xd0,0x48,0x83,0xc4,0x28,0x48,0x8b,0x83,0x3b,0x00,0x00,0x00,0x49,0x89,0xc7,0x5a,0x59,0x5b,0x58,0x41,0xff,0xe7,0x48,0x8b,0x04,0x24,0xc3,0x90,0x90,0x90,0x90,0x90,0x90,0x90,0x90,0x90,0x90,0x90,0x90,0x90,0x90,0x90,0x90,0x90,0x90,0x90,0x90,0x90,0x90,0x90,0x90 }; - oepva = context.Rip; - context.Rip = (ULONGLONG)injectaddr; - -#else - uint8_t injectcode[] = {0x50,0x53,0xe8,0x1e,0x00,0x00,0x00,0x8d,0x58,0xf9,0x8b,0x83,0x2d,0x00,0x00,0x00,0x50,0x8b,0x83,0x31,0x00,0x00,0x00,0xff,0xd0,0x8b,0x83,0x29,0x00,0x00,0x00,0x89,0xc7,0x5b,0x58,0xff,0xe7,0x8b,0x04,0x24,0xc3,0x90,0x90,0x90,0x90,0x90,0x90,0x90,0x90,0x90,0x90,0x90,0x90 }; - oepva = context.Eip; // origin eip at RtlUserThreadStart - context.Eip = (DWORD)injectaddr; -#endif - SetThreadContext(hthread, &context); - - char name_kernel32[] = { 'k', 'e', 'r', 'n', 'e', 'l', '3', '2', '.', 'd', 'l', 'l', '\0'}; - HMODULE kernel32 = GetModuleHandleA(name_kernel32); - char name_LoadLibraryA[] = { 'L', 'o', 'a', 'd', 'L', 'i', 'b', 'r', 'a', 'r', 'y', 'A', '\0' }; - FARPROC pfnLoadlibraryA = GetProcAddress(kernel32, name_LoadLibraryA); - size_t* pretva = (size_t*)(injectcode - + sizeof(injectcode) - 3 * sizeof(size_t)); - size_t *pdllnameva = (size_t*)(injectcode - + sizeof(injectcode) - 2 * sizeof(size_t)); - size_t* ploadlibraryva = (size_t*)(injectcode - + sizeof(injectcode) - 1 * sizeof(size_t)); - *pretva = (size_t)oepva; - *pdllnameva = (size_t)((size_t)injectaddr + sizeof(injectcode)); - *ploadlibraryva = (size_t)pfnLoadlibraryA; - - uint8_t* addr = (uint8_t*)injectaddr; - WriteProcessMemory(hprocess, addr, - injectcode, sizeof(injectcode), (SIZE_T*)&n); // copy shellcode - addr += sizeof(injectcode); - WriteProcessMemory(hprocess, addr, - dllpath, strlen(dllpath) + 1, (SIZE_T*)&n); // copy dll name - } - - ResumeThread(pi.hThread); - CloseHandle(pi.hThread); - return pi.dwProcessId; -} - -WINHOOKDEF WINHOOK_EXPORT -INLINE HANDLE winhook_getprocess(LPCWSTR exename) -{ - // Create toolhelp snapshot. - DWORD pid = 0; - HANDLE snapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0); - PROCESSENTRY32 process; - ZeroMemory(&process, sizeof(process)); - process.dwSize = sizeof(process); - - // Walkthrough all processes. - if (Process32First(snapshot, &process)) - { - do - { - if (_wcsicmp((const wchar_t*)process.szExeFile, exename) == 0) - { - pid = process.th32ProcessID; - break; - } - } while (Process32Next(snapshot, &process)); - } - CloseHandle(snapshot); - if (pid != 0) return OpenProcess(PROCESS_ALL_ACCESS, FALSE, pid); - return NULL; // Not found -} - -WINHOOKDEF WINHOOK_EXPORT -INLINE size_t winhook_getimagebase(HANDLE hprocess) -{ - //if (hprocess == GetCurrentProcess()) return (size_t)GetModuleHandleA(NULL); - HMODULE modules[1024]; // Array that receives the list of module handles - DWORD nmodules = 0; - char modulename[MAX_PATH] = {0}; - if (!EnumProcessModules(hprocess, modules, sizeof(modules), &nmodules)) - return 0; // impossible to read modules - if (!GetModuleFileNameExA(hprocess, modules[0], modulename, sizeof(modulename))) - return 0; // impossible to get module info - return (size_t)modules[0]; // module 0 is apparently always the EXE itself -} - -WINHOOKDEF WINHOOK_EXPORT -INLINE BOOL winhook_injectdll(HANDLE hprocess, LPCSTR dllname) -{ - LPVOID addr = VirtualAllocEx(hprocess, - 0, 0x100, MEM_COMMIT, PAGE_READWRITE); - SIZE_T count; - if (addr == NULL) return FALSE; - WriteProcessMemory(hprocess, - addr, dllname, strlen(dllname)+1, (SIZE_T*)&count); - - char name_kernel32[] = { 'k', 'e', 'r', 'n', 'e', 'l', '3', '2', '.', 'd', 'l', 'l', '\0' }; - HMODULE kernel32 = GetModuleHandleA(name_kernel32); - char name_LoadLibraryA[] = { 'L', 'o', 'a', 'd', 'L', 'i', 'b', 'r', 'a', 'r', 'y', 'A', '\0' }; - FARPROC pfnLoadlibraryA = GetProcAddress(kernel32, name_LoadLibraryA); - HANDLE hthread = CreateRemoteThread(hprocess, NULL, 0, - (LPTHREAD_START_ROUTINE)pfnLoadlibraryA, addr, 0, NULL); - - if (hthread == NULL) return FALSE; - WaitForSingleObject(hthread, -1); - VirtualFreeEx(hprocess, addr, 0x100, MEM_COMMIT); - - return TRUE; -} - -WINHOOKDEF WINHOOK_EXPORT -INLINE void winhook_installconsole() -{ - AllocConsole(); - freopen("CONOUT$", "w", stdout); -} - -// dynamic hook functions -WINHOOKDEF WINHOOK_EXPORT -INLINE BOOL winhook_patchmemoryex(HANDLE hprocess, - LPVOID addr, const void* buf, size_t bufsize) -{ - if (addr == NULL || buf == NULL) return FALSE; - DWORD oldprotect; - BOOL ret = VirtualProtectEx(hprocess, addr, - bufsize, PAGE_EXECUTE_READWRITE, &oldprotect); - if (ret) - { - size_t n = 0; - WriteProcessMemory(hprocess, addr, - buf, bufsize, (SIZE_T*)&n); - VirtualProtectEx(hprocess, addr, - bufsize, oldprotect, &oldprotect); - } - return ret; -} - -WINHOOKDEF WINHOOK_EXPORT -INLINE BOOL winhook_patchmemorysex(HANDLE hprocess, - LPVOID addrs[], void* bufs[], - size_t bufsizes[], int n) -{ - int ret = 0; - for (int i = 0; i < n; i++) - { - ret += winhook_patchmemoryex(hprocess, - addrs[i], bufs[i], bufsizes[i]); - } - return ret; -} - -INLINE int winhook_patchmemorypattern(const char *pattern) -{ - if (!pattern) return -1; - size_t imagebase = (size_t)GetModuleHandleA(NULL); - int res = 0; - int flag_rel = 0; - int j = 0; - while (pattern[j]) j++; - int patternlen = j; - DWORD oldprotect; - - for(int i=0; i='0' && c<='9') c -= '0'; - else if (c>='A' && c<='Z') c = c -'A' + 10; - else if (c>='a' && c<='z') c = c -'a' - 10; - else if (c=='\r' || c=='\n') {flag_nextline=1;break;} - else if (c==' ') continue; - else return -2; - addr = (addr<<4) + c; - } - if(flag_nextline) continue; - if(flag_rel) addr += imagebase; - - int n = 0; - int v = 0; - int start = i++; - for(int j=0;j<2;j++) - { - n = 0; - for(;pattern[i]!='\n' && i='0' && c<='9') c -= '0'; - else if (c>='A' && c<='Z') c = c - 'A' + 10; - else if (c>='a' && c<='z') c = c - 'a' + 10; - else if (c==';') break; - else continue; - n++; - if (j != 0) - { - v = (v << 4) + c; - if (!(n & 1)) - { - *(uint8_t*)(addr + (n>>1) -1) = v; - v = 0; - res++; - } - } - } - if(n&1) return -3; - if (j == 0) - { - i = start; - VirtualProtect((void*)addr, n>>1, PAGE_EXECUTE_READWRITE, &oldprotect); - } - else VirtualProtect((void*)addr, n>>1, oldprotect, &oldprotect); - } - flag_rel = 0; - } - return res; -} - -INLINE int winhook_patchmemory1337ex(HANDLE hprocess, const char* pattern, size_t base, BOOL revert) -{ -#define IS_ENDLINE(c) (c==';' || c=='\r' || c=='\n') - enum FLAG1337 { - RVA1337, - OLDBYTE1337, - NEWBYTE1337 - } flag1337 = RVA1337; - - if (hprocess == NULL) return -1; - - int res = 0; - int i = 0; - while (pattern[i]) i++; - int patternlen = i; - i = 0; - while (pattern[i] != '>') i++; // title line - while (!IS_ENDLINE(pattern[i])) i++; - while (IS_ENDLINE(pattern[i])) i++; - - size_t rva = 0; - uint8_t oldbyte = 0, newbyte = 0; - for (; i < patternlen; i++) - { - char c = pattern[i]; - if (c == ':') // oldbyte indicator - { - flag1337 = OLDBYTE1337; - } - else if (c == '-') // newbyte indicator - { - if (pattern[i + 1] != '>') return -1; - flag1337 = NEWBYTE1337; - i++; - } - else if (IS_ENDLINE(c)) // flush patch - { - if (flag1337 == RVA1337) continue; - uint8_t* patchbyte = revert ? &oldbyte : &newbyte; - winhook_patchmemoryex(hprocess, (LPVOID)(base + rva), patchbyte, 1); - flag1337 = RVA1337; - rva = 0; - oldbyte = 0; - newbyte = 0; - res++; - } - else if (c == ' ') - { - continue; - } - else - { - if (c >= '0' && c <= '9') c -= '0'; - else if (c >= 'A' && c <= 'Z') c = c - 'A' + 10; - else if (c >= 'a' && c <= 'z') c = c - 'a' + 10; - else continue; - switch (flag1337) - { - case RVA1337: - rva = (rva << 4) | (uint8_t)c; - break; - case OLDBYTE1337: - oldbyte = (oldbyte << 4) | (uint8_t)c; - break; - case NEWBYTE1337: - newbyte = (newbyte << 4) | (uint8_t)c; - break; - } - } - } - return res; -} - -INLINE int winhook_patchmemoryipsex(HANDLE hprocess, const char* pattern, size_t base) -{ -#define BYTE3_TO_UINT_BIGENDIAN(bp) \ - (((unsigned int)(bp)[0] << 16) & 0x00FF0000) | \ - (((unsigned int)(bp)[1] << 8) & 0x0000FF00) | \ - ((unsigned int)(bp)[2] & 0x000000FF) - -#define BYTE2_TO_UINT_BIGENDIAN(bp) \ - (((unsigned int)(bp)[0] << 8) & 0xFF00) | \ - ((unsigned int) (bp)[1] & 0x00FF) - - if(strncmp(pattern, "PATCH", 5) !=0 ) return -1; - int res = 0; - const uint8_t* p = (uint8_t*)pattern + 5; - while (strncmp((char*)p, "EOF", 3) != 0) - { - unsigned int offset = BYTE3_TO_UINT_BIGENDIAN(p); - unsigned int size = BYTE2_TO_UINT_BIGENDIAN(p + 3); - p += 5; - if (size == 0) // use RLE compress - { - unsigned int size_rle = BYTE2_TO_UINT_BIGENDIAN(p); - return -2; // not implemented yet - } - else - { - size_t addr = base + offset; - winhook_patchmemoryex(hprocess, (LPVOID)addr, p, size); - p += size; - res += size; - } - } - return res; -} - -INLINE void* winhook_searchmemory(void* addr, size_t memsize, - const char* pattern, size_t* pmatchsize) -{ - size_t i = 0; - int matchend = 0; - void* matchaddr = NULL; - while (i < memsize) - { - int j = 0; - int matchflag = 1; - matchend = 0; - while (pattern[j]) - { - if (pattern[j] == 0x20) - { - j++; - continue; - } - char _c1 = (((char*)addr)[i+matchend]>>4) & 0x0f; - _c1 = _c1 < 10 ? _c1 + '0' : (_c1 - 10) + 'A'; - char _c2 = (((char*)addr)[i+matchend]&0xf) & 0x0f; - _c2 = _c2 < 10 ? _c2 + '0' : (_c2 - 10) + 'A'; - if (pattern[j] != '?') - { - if (_c1 != pattern[j] && _c1 + 0x20 != pattern[j]) - { - matchflag = 0; - break; - } - } - if (pattern[j + 1] != '?') - { - if (_c2 != pattern[j+1] && _c2 + 0x20 != pattern[j+1]) - { - matchflag = 0; - break; - } - } - j += 2; - matchend++; - } - if (matchflag) - { - matchaddr = (void*)((uint8_t*)addr + i); - break; - } - i++; - } - if (pmatchsize) *pmatchsize = matchend; - return matchaddr; -} - -WINHOOKDEF WINHOOK_EXPORT -INLINE void* winhook_searchmemoryex(HANDLE hprocess, - void* addr, size_t memsize, - const char* pattern, size_t* pmatchsize) -{ - void* buf = VirtualAlloc(NULL, - memsize, MEM_COMMIT, PAGE_READWRITE); - size_t bufsize = 0; - ReadProcessMemory(hprocess, addr, - buf, memsize, (SIZE_T*)&bufsize); - void* matchaddr = winhook_searchmemory( - buf, memsize, pattern, pmatchsize); - VirtualFree(buf, 0, MEM_RELEASE); - if (!matchaddr) return matchaddr; - size_t offset = (size_t)matchaddr - (size_t)buf; - return (void*)((uint8_t*)addr + offset); -} - -WINHOOKDEF WINHOOK_EXPORT -INLINE BOOL winhook_iathookpe(LPCSTR targetDllName, - void* mempe, PROC pfnOrg, PROC pfnNew) -{ - size_t imagebase = (size_t)mempe; - PIMAGE_DOS_HEADER pDosHeader = (PIMAGE_DOS_HEADER)imagebase; - PIMAGE_NT_HEADERS pNtHeader = (PIMAGE_NT_HEADERS) - ((uint8_t*)imagebase + pDosHeader->e_lfanew); - PIMAGE_FILE_HEADER pFileHeader = &pNtHeader->FileHeader; - PIMAGE_OPTIONAL_HEADER pOptHeader = &pNtHeader->OptionalHeader; - PIMAGE_DATA_DIRECTORY pDataDirectory = pOptHeader->DataDirectory; - PIMAGE_DATA_DIRECTORY pImpEntry = - &pDataDirectory[IMAGE_DIRECTORY_ENTRY_IMPORT]; - PIMAGE_IMPORT_DESCRIPTOR pImpDescriptor = - (PIMAGE_IMPORT_DESCRIPTOR)(imagebase + pImpEntry->VirtualAddress); - - DWORD dwOldProtect = 0; - for (; pImpDescriptor->Name; pImpDescriptor++) - { - // find the dll IMPORT_DESCRIPTOR - LPCSTR pDllName = (LPCSTR)(imagebase + pImpDescriptor->Name); - if (!_stricmp(pDllName, targetDllName)) // ignore case - { - PIMAGE_THUNK_DATA pFirstThunk = (PIMAGE_THUNK_DATA) - (imagebase + pImpDescriptor->FirstThunk); - // find the iat function va - for (; pFirstThunk->u1.Function; pFirstThunk++) - { - if (pFirstThunk->u1.Function == (size_t)pfnOrg) - { - VirtualProtect((LPVOID)&pFirstThunk->u1.Function, - 4, PAGE_EXECUTE_READWRITE, &dwOldProtect); - pFirstThunk->u1.Function = (size_t)pfnNew; - VirtualProtect((LPVOID)&pFirstThunk->u1.Function, - 4, dwOldProtect, &dwOldProtect); - return TRUE; - } - } - } - } - return FALSE; -} - -#ifndef WINHOOK_NOINLINEHOOK -#ifdef WINHOOK_USEDETOURS -#include "detours.h" -WINHOOKDEF WINHOOK_EXPORT -int winhook_inlinehooks(PVOID pfnTargets[], - PVOID pfnNews[], PVOID pfnOlds[], size_t n) -{ - int i=0; - DetourRestoreAfterWith(); - DetourTransactionBegin(); - DetourUpdateThread(GetCurrentThread()); - for(int i=0; i + +#ifndef WINHOOKDEF +#ifdef WINHOOK_STATIC +#define WINHOOKDEF static +#else +#define WINHOOKDEF extern +#endif +#endif + +#ifndef WINHOOK_SHARED +#define WINHOOK_EXPORT +#else +#ifdef _WIN32 +#define WINHOOK_EXPORT __declspec(dllexport) +#else +#define WINHOOK_EXPORT __attribute__((visibility("default"))) +#endif +#endif + +#ifndef INLINE +#ifdef WINHOOK_USESHELLCODE +#if defined(_MSC_VER) +#define INLINE __forceinline +#else // tcc, gcc not support inline export ... +#define INLINE +#endif +#else +#define INLINE +#endif +#endif + +#ifdef __cplusplus +extern "C" { +#endif +// loader functions +/** + * start a exe and inject dll into exe + * return pid +*/ +WINHOOKDEF WINHOOK_EXPORT +INLINE DWORD winhook_startexeinject(LPCSTR exepath, + LPSTR cmdstr, LPCSTR dllpath); + +/** + * start a exe by CreateProcess + * @return pid +*/ +#define winhook_startexe(exepath, cmdstr)\ + winhook_startexeinject(exepath, cmdstr, NULL) + + +/** + * get the process handle by exename +*/ +WINHOOKDEF WINHOOK_EXPORT +INLINE HANDLE winhook_getprocess(LPCWSTR exename); + +/** + * get the other process image base +*/ +WINHOOKDEF WINHOOK_EXPORT +INLINE size_t winhook_getimagebase(HANDLE hprocess); + +/** + * dynamic inject a dll into a process +*/ +WINHOOKDEF WINHOOK_EXPORT +INLINE BOOL winhook_injectdll(HANDLE hprocess, LPCSTR dllname); + +/** + * alloc a console for the program +*/ +WINHOOKDEF WINHOOK_EXPORT +INLINE void winhook_installconsole(); + + +// dynamic hook functions +/** + * patch addr by buf with bufsize +*/ +WINHOOKDEF WINHOOK_EXPORT +INLINE BOOL winhook_patchmemoryex(HANDLE hprocess, + LPVOID addr, const void* buf, size_t bufsize); + +#define winhook_patchmemory(addr, buf, bufsize)\ + winhook_patchmemoryex(GetCurrentProcess(), addr, buf, bufsize) + +/** + * batch patch memories +*/ +WINHOOKDEF WINHOOK_EXPORT +INLINE BOOL winhook_patchmemorysex(HANDLE hprocess, + LPVOID addrs[], void* bufs[], + size_t bufsizes[], int n); + +#define winhook_patchmemorys(addrs, bufs, bufsizes, n)\ + winhook_patchmemorysex(GetCurrentProcess(), addrs, bufs, bufsizes, n) + +/** + * patch memory with pattern, + * @param pattern + * skip '#' line, + for reative address, then multi byte code (hex) + * 00400000: ff 90 + * +3f00: 90 90 90 90 + * +3f06: 90; +3f08: 90 + * @return patch bytes number, error < 0 +*/ +WINHOOKDEF WINHOOK_EXPORT +INLINE int winhook_patchmemorypattern(const char *pattern); + +/** + * patch memory with pattern 1337 by x64dbg, use rva + * can use ';' instead of '\r' '\n' +*/ +WINHOOKDEF WINHOOK_EXPORT +INLINE int winhook_patchmemory1337ex(HANDLE hprocess, const char* pattern, size_t base, BOOL revert); + +#define winhook_patchmemory1337(pattern, base, revert) \ + winhook_patchmemory1337ex(GetCurrentProcess(), pattern, base, revert) + +/** + * patch memory with pattern ips(International Patching System) + * specifications at https://zerosoft.zophar.net/ips.php + * addr is relative to base, big endian +*/ +WINHOOKDEF WINHOOK_EXPORT +INLINE int winhook_patchmemoryipsex(HANDLE hprocess, const char* pattern, size_t base); + +#define winhook_patchmemoryips(pattern, base) \ + winhook_patchmemoryipsex(GetCurrentProcess(), pattern, base) + +/** + * search the pattern like "ab 12 ?? 34" + * @return the matched address +*/ +WINHOOKDEF WINHOOK_EXPORT +INLINE void* winhook_searchmemory(void* addr, size_t memsize, + const char* pattern, size_t *pmatchsize); + +WINHOOKDEF WINHOOK_EXPORT +INLINE void* winhook_searchmemoryex(HANDLE hprocess, + void* addr, size_t memsize, + const char* pattern, size_t* pmatchsize); + +/** + * winhook_iathookmodule is for windows dll, + * @param moduleDllName is which dll to hook iat +*/ +WINHOOKDEF WINHOOK_EXPORT +INLINE BOOL winhook_iathookpe(LPCSTR targetDllName, + void* mempe, PROC pfnOrg, PROC pfnNew); + +#define winhook_iathookmodule(targetDllName, moduleDllName, pfnOrg, pfnNew)\ + winhook_iathookpe(targetDllName, GetModuleHandle(moduleDllName), pfnOrg, pfnNew) + +/** + * iat dynamiclly hook, + * replace the @param pfgNew with @param pfnOrg function + * @param targetDllName like "user32.dll", "kernel32.dll" +*/ +#define winhook_iathook(targetDllName, pfnOrg, pfgNew)\ + winhook_iathookmodule(targetDllName, NULL, pfnOrg, pfgNew) + +/** + * inline hooks wrapper, + * @param pfnTargets -> @param pfnNews, save origin pointers in @param pfnOlds + * @return: success hook numbers +*/ +WINHOOKDEF WINHOOK_EXPORT +int winhook_inlinehooks(PVOID pfnTargets[], + PVOID pfnNews[], PVOID pfnOlds[], size_t n); + +WINHOOKDEF WINHOOK_EXPORT +int winhook_inlineunhooks(PVOID pfnTargets[], + PVOID pfnNews[], PVOID pfnOlds[], size_t n); + +#endif + +#ifdef __cplusplus +} +#endif + +#ifdef WINHOOK_IMPLEMENTATION +#include +#include +#include +#include +#include +#include + +#ifdef WINHOOK_USESHELLCODE +#define WINDYN_IMPLEMENTATION +#define WINDYN_STATIC +#include "windyn.h" +#define strlen windyn_strlen +#define _stricmp windyn_stricmp +#define _wcsicmp windyn_wcsicmp +#define GetModuleHandleA windyn_GetModuleHandleA +#define LoadLibraryA windyn_LoadLibraryA +#define GetProcAddress windyn_GetProcAddress +#define VirtualAllocEx windyn_VirtualAllocEx +#endif + +// loader functions +WINHOOKDEF WINHOOK_EXPORT +INLINE DWORD winhook_startexeinject(LPCSTR exepath, + LPSTR cmdstr, LPCSTR dllpath) +{ + STARTUPINFOA si = {0}; + PROCESS_INFORMATION pi = {0}; + si.cb = sizeof(STARTUPINFOA); + if (!CreateProcessA(exepath, cmdstr, + NULL, NULL, FALSE, CREATE_SUSPENDED, NULL, NULL, &si, &pi)) + return 0; + + if (dllpath) // inject dll to process + { + size_t n = 0; + HANDLE hprocess = pi.hProcess; + HANDLE hthread = pi.hThread; + LPVOID injectaddr = VirtualAllocEx(hprocess, + 0, 0x1000, MEM_COMMIT, PAGE_EXECUTE_READWRITE); + size_t oepva = 0; + + // prepare shellcode + CONTEXT context = { 0 }; + context.ContextFlags = CONTEXT_ALL; + GetThreadContext(hthread, &context); +#ifdef _WIN64 + uint8_t injectcode[] = {0x50,0x53,0x51,0x52,0xe8,0x2d,0x00,0x00,0x00,0x48,0x8d,0x58,0xf7,0x48,0x83,0xec,0x28,0x48,0x8b,0x8b,0x43,0x00,0x00,0x00,0x48,0x8b,0x83,0x4b,0x00,0x00,0x00,0xff,0xd0,0x48,0x83,0xc4,0x28,0x48,0x8b,0x83,0x3b,0x00,0x00,0x00,0x49,0x89,0xc7,0x5a,0x59,0x5b,0x58,0x41,0xff,0xe7,0x48,0x8b,0x04,0x24,0xc3,0x90,0x90,0x90,0x90,0x90,0x90,0x90,0x90,0x90,0x90,0x90,0x90,0x90,0x90,0x90,0x90,0x90,0x90,0x90,0x90,0x90,0x90,0x90,0x90 }; + oepva = context.Rip; + context.Rip = (ULONGLONG)injectaddr; + +#else + uint8_t injectcode[] = {0x50,0x53,0xe8,0x1e,0x00,0x00,0x00,0x8d,0x58,0xf9,0x8b,0x83,0x2d,0x00,0x00,0x00,0x50,0x8b,0x83,0x31,0x00,0x00,0x00,0xff,0xd0,0x8b,0x83,0x29,0x00,0x00,0x00,0x89,0xc7,0x5b,0x58,0xff,0xe7,0x8b,0x04,0x24,0xc3,0x90,0x90,0x90,0x90,0x90,0x90,0x90,0x90,0x90,0x90,0x90,0x90 }; + oepva = context.Eip; // origin eip at RtlUserThreadStart + context.Eip = (DWORD)injectaddr; +#endif + SetThreadContext(hthread, &context); + + char name_kernel32[] = { 'k', 'e', 'r', 'n', 'e', 'l', '3', '2', '.', 'd', 'l', 'l', '\0'}; + HMODULE kernel32 = GetModuleHandleA(name_kernel32); + char name_LoadLibraryA[] = { 'L', 'o', 'a', 'd', 'L', 'i', 'b', 'r', 'a', 'r', 'y', 'A', '\0' }; + FARPROC pfnLoadlibraryA = GetProcAddress(kernel32, name_LoadLibraryA); + size_t* pretva = (size_t*)(injectcode + + sizeof(injectcode) - 3 * sizeof(size_t)); + size_t *pdllnameva = (size_t*)(injectcode + + sizeof(injectcode) - 2 * sizeof(size_t)); + size_t* ploadlibraryva = (size_t*)(injectcode + + sizeof(injectcode) - 1 * sizeof(size_t)); + *pretva = (size_t)oepva; + *pdllnameva = (size_t)((size_t)injectaddr + sizeof(injectcode)); + *ploadlibraryva = (size_t)pfnLoadlibraryA; + + uint8_t* addr = (uint8_t*)injectaddr; + WriteProcessMemory(hprocess, addr, + injectcode, sizeof(injectcode), (SIZE_T*)&n); // copy shellcode + addr += sizeof(injectcode); + WriteProcessMemory(hprocess, addr, + dllpath, strlen(dllpath) + 1, (SIZE_T*)&n); // copy dll name + } + + ResumeThread(pi.hThread); + CloseHandle(pi.hThread); + return pi.dwProcessId; +} + +WINHOOKDEF WINHOOK_EXPORT +INLINE HANDLE winhook_getprocess(LPCWSTR exename) +{ + // Create toolhelp snapshot. + DWORD pid = 0; + HANDLE snapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0); + PROCESSENTRY32 process; + ZeroMemory(&process, sizeof(process)); + process.dwSize = sizeof(process); + + // Walkthrough all processes. + if (Process32First(snapshot, &process)) + { + do + { + if (_wcsicmp((const wchar_t*)process.szExeFile, exename) == 0) + { + pid = process.th32ProcessID; + break; + } + } while (Process32Next(snapshot, &process)); + } + CloseHandle(snapshot); + if (pid != 0) return OpenProcess(PROCESS_ALL_ACCESS, FALSE, pid); + return NULL; // Not found +} + +WINHOOKDEF WINHOOK_EXPORT +INLINE size_t winhook_getimagebase(HANDLE hprocess) +{ + //if (hprocess == GetCurrentProcess()) return (size_t)GetModuleHandleA(NULL); + HMODULE modules[1024]; // Array that receives the list of module handles + DWORD nmodules = 0; + char modulename[MAX_PATH] = {0}; + if (!EnumProcessModules(hprocess, modules, sizeof(modules), &nmodules)) + return 0; // impossible to read modules + if (!GetModuleFileNameExA(hprocess, modules[0], modulename, sizeof(modulename))) + return 0; // impossible to get module info + return (size_t)modules[0]; // module 0 is apparently always the EXE itself +} + +WINHOOKDEF WINHOOK_EXPORT +INLINE BOOL winhook_injectdll(HANDLE hprocess, LPCSTR dllname) +{ + LPVOID addr = VirtualAllocEx(hprocess, + 0, 0x100, MEM_COMMIT, PAGE_READWRITE); + SIZE_T count; + if (addr == NULL) return FALSE; + WriteProcessMemory(hprocess, + addr, dllname, strlen(dllname)+1, (SIZE_T*)&count); + + char name_kernel32[] = { 'k', 'e', 'r', 'n', 'e', 'l', '3', '2', '.', 'd', 'l', 'l', '\0' }; + HMODULE kernel32 = GetModuleHandleA(name_kernel32); + char name_LoadLibraryA[] = { 'L', 'o', 'a', 'd', 'L', 'i', 'b', 'r', 'a', 'r', 'y', 'A', '\0' }; + FARPROC pfnLoadlibraryA = GetProcAddress(kernel32, name_LoadLibraryA); + HANDLE hthread = CreateRemoteThread(hprocess, NULL, 0, + (LPTHREAD_START_ROUTINE)pfnLoadlibraryA, addr, 0, NULL); + + if (hthread == NULL) return FALSE; + WaitForSingleObject(hthread, -1); + VirtualFreeEx(hprocess, addr, 0x100, MEM_COMMIT); + + return TRUE; +} + +WINHOOKDEF WINHOOK_EXPORT +INLINE void winhook_installconsole() +{ + AllocConsole(); + freopen("CONOUT$", "w", stdout); +} + +// dynamic hook functions +WINHOOKDEF WINHOOK_EXPORT +INLINE BOOL winhook_patchmemoryex(HANDLE hprocess, + LPVOID addr, const void* buf, size_t bufsize) +{ + if (addr == NULL || buf == NULL) return FALSE; + DWORD oldprotect; + BOOL ret = VirtualProtectEx(hprocess, addr, + bufsize, PAGE_EXECUTE_READWRITE, &oldprotect); + if (ret) + { + size_t n = 0; + WriteProcessMemory(hprocess, addr, + buf, bufsize, (SIZE_T*)&n); + VirtualProtectEx(hprocess, addr, + bufsize, oldprotect, &oldprotect); + } + return ret; +} + +WINHOOKDEF WINHOOK_EXPORT +INLINE BOOL winhook_patchmemorysex(HANDLE hprocess, + LPVOID addrs[], void* bufs[], + size_t bufsizes[], int n) +{ + int ret = 0; + for (int i = 0; i < n; i++) + { + ret += winhook_patchmemoryex(hprocess, + addrs[i], bufs[i], bufsizes[i]); + } + return ret; +} + +INLINE int winhook_patchmemorypattern(const char *pattern) +{ + if (!pattern) return -1; + size_t imagebase = (size_t)GetModuleHandleA(NULL); + int res = 0; + int flag_rel = 0; + int j = 0; + while (pattern[j]) j++; + int patternlen = j; + DWORD oldprotect; + + for(int i=0; i='0' && c<='9') c -= '0'; + else if (c>='A' && c<='Z') c = c -'A' + 10; + else if (c>='a' && c<='z') c = c -'a' - 10; + else if (c=='\r' || c=='\n') {flag_nextline=1;break;} + else if (c==' ') continue; + else return -2; + addr = (addr<<4) + c; + } + if(flag_nextline) continue; + if(flag_rel) addr += imagebase; + + int n = 0; + int v = 0; + int start = i++; + for(int j=0;j<2;j++) + { + n = 0; + for(;pattern[i]!='\n' && i='0' && c<='9') c -= '0'; + else if (c>='A' && c<='Z') c = c - 'A' + 10; + else if (c>='a' && c<='z') c = c - 'a' + 10; + else if (c==';') break; + else continue; + n++; + if (j != 0) + { + v = (v << 4) + c; + if (!(n & 1)) + { + *(uint8_t*)(addr + (n>>1) -1) = v; + v = 0; + res++; + } + } + } + if(n&1) return -3; + if (j == 0) + { + i = start; + VirtualProtect((void*)addr, n>>1, PAGE_EXECUTE_READWRITE, &oldprotect); + } + else VirtualProtect((void*)addr, n>>1, oldprotect, &oldprotect); + } + flag_rel = 0; + } + return res; +} + +INLINE int winhook_patchmemory1337ex(HANDLE hprocess, const char* pattern, size_t base, BOOL revert) +{ +#define IS_ENDLINE(c) (c==';' || c=='\r' || c=='\n') + enum FLAG1337 { + RVA1337, + OLDBYTE1337, + NEWBYTE1337 + } flag1337 = RVA1337; + + if (hprocess == NULL) return -1; + + int res = 0; + int i = 0; + while (pattern[i]) i++; + int patternlen = i; + i = 0; + while (pattern[i] != '>') i++; // title line + while (!IS_ENDLINE(pattern[i])) i++; + while (IS_ENDLINE(pattern[i])) i++; + + size_t rva = 0; + uint8_t oldbyte = 0, newbyte = 0; + for (; i < patternlen; i++) + { + char c = pattern[i]; + if (c == ':') // oldbyte indicator + { + flag1337 = OLDBYTE1337; + } + else if (c == '-') // newbyte indicator + { + if (pattern[i + 1] != '>') return -1; + flag1337 = NEWBYTE1337; + i++; + } + else if (IS_ENDLINE(c)) // flush patch + { + if (flag1337 == RVA1337) continue; + uint8_t* patchbyte = revert ? &oldbyte : &newbyte; + winhook_patchmemoryex(hprocess, (LPVOID)(base + rva), patchbyte, 1); + flag1337 = RVA1337; + rva = 0; + oldbyte = 0; + newbyte = 0; + res++; + } + else if (c == ' ') + { + continue; + } + else + { + if (c >= '0' && c <= '9') c -= '0'; + else if (c >= 'A' && c <= 'Z') c = c - 'A' + 10; + else if (c >= 'a' && c <= 'z') c = c - 'a' + 10; + else continue; + switch (flag1337) + { + case RVA1337: + rva = (rva << 4) | (uint8_t)c; + break; + case OLDBYTE1337: + oldbyte = (oldbyte << 4) | (uint8_t)c; + break; + case NEWBYTE1337: + newbyte = (newbyte << 4) | (uint8_t)c; + break; + } + } + } + return res; +} + +INLINE int winhook_patchmemoryipsex(HANDLE hprocess, const char* pattern, size_t base) +{ +#define BYTE3_TO_UINT_BIGENDIAN(bp) \ + (((unsigned int)(bp)[0] << 16) & 0x00FF0000) | \ + (((unsigned int)(bp)[1] << 8) & 0x0000FF00) | \ + ((unsigned int)(bp)[2] & 0x000000FF) + +#define BYTE2_TO_UINT_BIGENDIAN(bp) \ + (((unsigned int)(bp)[0] << 8) & 0xFF00) | \ + ((unsigned int) (bp)[1] & 0x00FF) + + if(strncmp(pattern, "PATCH", 5) !=0 ) return -1; + int res = 0; + const uint8_t* p = (uint8_t*)pattern + 5; + while (strncmp((char*)p, "EOF", 3) != 0) + { + unsigned int offset = BYTE3_TO_UINT_BIGENDIAN(p); + unsigned int size = BYTE2_TO_UINT_BIGENDIAN(p + 3); + p += 5; + if (size == 0) // use RLE compress + { + unsigned int size_rle = BYTE2_TO_UINT_BIGENDIAN(p); + return -2; // not implemented yet + } + else + { + size_t addr = base + offset; + winhook_patchmemoryex(hprocess, (LPVOID)addr, p, size); + p += size; + res += size; + } + } + return res; +} + +INLINE void* winhook_searchmemory(void* addr, size_t memsize, + const char* pattern, size_t* pmatchsize) +{ + size_t i = 0; + int matchend = 0; + void* matchaddr = NULL; + while (i < memsize) + { + int j = 0; + int matchflag = 1; + matchend = 0; + while (pattern[j]) + { + if (pattern[j] == 0x20) + { + j++; + continue; + } + char _c1 = (((char*)addr)[i+matchend]>>4) & 0x0f; + _c1 = _c1 < 10 ? _c1 + '0' : (_c1 - 10) + 'A'; + char _c2 = (((char*)addr)[i+matchend]&0xf) & 0x0f; + _c2 = _c2 < 10 ? _c2 + '0' : (_c2 - 10) + 'A'; + if (pattern[j] != '?') + { + if (_c1 != pattern[j] && _c1 + 0x20 != pattern[j]) + { + matchflag = 0; + break; + } + } + if (pattern[j + 1] != '?') + { + if (_c2 != pattern[j+1] && _c2 + 0x20 != pattern[j+1]) + { + matchflag = 0; + break; + } + } + j += 2; + matchend++; + } + if (matchflag) + { + matchaddr = (void*)((uint8_t*)addr + i); + break; + } + i++; + } + if (pmatchsize) *pmatchsize = matchend; + return matchaddr; +} + +WINHOOKDEF WINHOOK_EXPORT +INLINE void* winhook_searchmemoryex(HANDLE hprocess, + void* addr, size_t memsize, + const char* pattern, size_t* pmatchsize) +{ + void* buf = VirtualAlloc(NULL, + memsize, MEM_COMMIT, PAGE_READWRITE); + size_t bufsize = 0; + ReadProcessMemory(hprocess, addr, + buf, memsize, (SIZE_T*)&bufsize); + void* matchaddr = winhook_searchmemory( + buf, memsize, pattern, pmatchsize); + VirtualFree(buf, 0, MEM_RELEASE); + if (!matchaddr) return matchaddr; + size_t offset = (size_t)matchaddr - (size_t)buf; + return (void*)((uint8_t*)addr + offset); +} + +WINHOOKDEF WINHOOK_EXPORT +INLINE BOOL winhook_iathookpe(LPCSTR targetDllName, + void* mempe, PROC pfnOrg, PROC pfnNew) +{ + size_t imagebase = (size_t)mempe; + PIMAGE_DOS_HEADER pDosHeader = (PIMAGE_DOS_HEADER)imagebase; + PIMAGE_NT_HEADERS pNtHeader = (PIMAGE_NT_HEADERS) + ((uint8_t*)imagebase + pDosHeader->e_lfanew); + PIMAGE_FILE_HEADER pFileHeader = &pNtHeader->FileHeader; + PIMAGE_OPTIONAL_HEADER pOptHeader = &pNtHeader->OptionalHeader; + PIMAGE_DATA_DIRECTORY pDataDirectory = pOptHeader->DataDirectory; + PIMAGE_DATA_DIRECTORY pImpEntry = + &pDataDirectory[IMAGE_DIRECTORY_ENTRY_IMPORT]; + PIMAGE_IMPORT_DESCRIPTOR pImpDescriptor = + (PIMAGE_IMPORT_DESCRIPTOR)(imagebase + pImpEntry->VirtualAddress); + + DWORD dwOldProtect = 0; + for (; pImpDescriptor->Name; pImpDescriptor++) + { + // find the dll IMPORT_DESCRIPTOR + LPCSTR pDllName = (LPCSTR)(imagebase + pImpDescriptor->Name); + if (!_stricmp(pDllName, targetDllName)) // ignore case + { + PIMAGE_THUNK_DATA pFirstThunk = (PIMAGE_THUNK_DATA) + (imagebase + pImpDescriptor->FirstThunk); + // find the iat function va + for (; pFirstThunk->u1.Function; pFirstThunk++) + { + if (pFirstThunk->u1.Function == (size_t)pfnOrg) + { + VirtualProtect((LPVOID)&pFirstThunk->u1.Function, + 4, PAGE_EXECUTE_READWRITE, &dwOldProtect); + pFirstThunk->u1.Function = (size_t)pfnNew; + VirtualProtect((LPVOID)&pFirstThunk->u1.Function, + 4, dwOldProtect, &dwOldProtect); + return TRUE; + } + } + } + } + return FALSE; +} + +#ifndef WINHOOK_NOINLINEHOOK +#ifdef WINHOOK_USEDETOURS +#error "detours are not included in this program" +#include "detours.h" +WINHOOKDEF WINHOOK_EXPORT +int winhook_inlinehooks(PVOID pfnTargets[], + PVOID pfnNews[], PVOID pfnOlds[], size_t n) +{ + int i=0; + DetourRestoreAfterWith(); + DetourTransactionBegin(); + DetourUpdateThread(GetCurrentThread()); + for(int i=0; i -#include -#include - -#ifndef WINPEDEF -#ifdef WINPE_STATIC -#define WINPEDEF static -#else -#define WINPEDEF extern -#endif -#endif - -#ifndef WINPE_SHARED -#define WINPE_EXPORT -#else -#if defined(_WIN32) -#define WINPE_EXPORT __declspec(dllexport) -#else -#define WINPE_EXPORT __attribute__((visibility("default"))) -#endif -#endif - -#if defined(_WIN32) -#ifndef STDCALL -#define STDCALL __stdcall -#endif -#ifdef NAKED -#define NAKED __declspec(naked) -#endif -#else -#ifndef STDCALL -#define STDCALL __attribute__((stdcall)) -#endif -#ifdef NAKED -#define NAKED __attribute__((naked)) -#endif -#endif - -#ifndef INLINE -#if defined(_MSC_VER) -#define INLINE __forceinline -#else // tcc, gcc not support inline export, tcc inline will output nofunction ... -#define INLINE -#endif -#endif - -#ifdef __cplusplus -extern "C" { -#endif -typedef struct _RELOCOFFSET -{ - WORD offset : 12; - WORD type : 4; -}RELOCOFFSET,*PRELOCOFFSET; - -typedef int bool_t; - -typedef HMODULE (WINAPI *PFN_LoadLibraryA)( - LPCSTR lpLibFileName); - -typedef FARPROC (WINAPI *PFN_GetProcAddress)( - HMODULE hModule, LPCSTR lpProcName); - -typedef PFN_GetProcAddress PFN_GetProcRVA; - -typedef LPVOID (WINAPI *PFN_VirtualAlloc)( - LPVOID lpAddress, SIZE_T dwSize, - DWORD flAllocationType, DWORD flProtect); - -typedef BOOL (WINAPI *PFN_VirtualFree)( - LPVOID lpAddress, SIZE_T dwSize, - DWORD dwFreeType); - -typedef BOOL (WINAPI *PFN_VirtualProtect)( - LPVOID lpAddress, SIZE_T dwSize, - DWORD flNewProtect, PDWORD lpflOldProtect); - -typedef SIZE_T (WINAPI *PFN_VirtualQuery)( - LPCVOID lpAddress, - PMEMORY_BASIC_INFORMATION lpBuffer, - SIZE_T dwLength); - -typedef BOOL (WINAPI *PFN_DllMain)(HINSTANCE hinstDLL, - DWORD fdwReason, LPVOID lpReserved ); - -#define WINPE_LDFLAG_MEMALLOC 0x1 -#define WINPE_LDFLAG_MEMFIND 0x2 - -// PE high order fnctions -/* - load the origin rawpe file in memory buffer by mem align - mempe means the pe in memory alignment - return mempe buffer, memsize -*/ -WINPEDEF WINPE_EXPORT -void* STDCALL winpe_memload_file(const char *path, - size_t *pmemsize, bool_t same_align); - -/* - load the overlay data in a pe file - return overlay buf, overlay size -*/ -WINPEDEF WINPE_EXPORT -void* STDCALL winpe_overlayload_file(const char *path, - size_t *poverlaysize); - -/* - similar to LoadlibrayA, will call dllentry - will load the mempe in a valid imagebase - return hmodule base -*/ -WINPEDEF WINPE_EXPORT -INLINE void* STDCALL winpe_memLoadLibrary(void *mempe); - -/* - if imagebase==0, will load on mempe, or in imagebase - will load the mempe in a valid imagebase, flag as below: - WINPE_LDFLAG_MEMALLOC 0x1, will alloc memory to imagebase - WINPE_LDFLAG_MEMFIND 0x2, will find a valid space, - must combined with WINPE_LDFLAG_MEMALLOC - return hmodule base -*/ -WINPEDEF WINPE_EXPORT -INLINE void* STDCALL winpe_memLoadLibraryEx(void *mempe, - size_t imagebase, DWORD flag, - PFN_LoadLibraryA pfnLoadLibraryA, - PFN_GetProcAddress pfnGetProcAddress); - -/* - similar to FreeLibrary, will call dllentry - return true or false -*/ -WINPEDEF WINPE_EXPORT -INLINE BOOL STDCALL winpe_memFreeLibrary(void *mempe); - -/* - FreeLibraryEx with VirtualFree custom function - return true or false -*/ -WINPEDEF WINPE_EXPORT -INLINE BOOL STDCALL winpe_memFreeLibraryEx(void *mempe, - PFN_LoadLibraryA pfnLoadLibraryA, - PFN_GetProcAddress pfnGetProcAddress); - - -/* - similar to GetProcAddress - return function va -*/ -WINPEDEF WINPE_EXPORT -INLINE PROC STDCALL winpe_memGetProcAddress( - void *mempe, const char *funcname); - -// PE query functions -/* - use peb and ldr list, to obtain to find kernel32.dll address - return kernel32.dll address -*/ -WINPEDEF WINPE_EXPORT -INLINE void* winpe_findkernel32(); - -/* - use peb and ldr list, similar as GetModuleHandleA - return ldr module address -*/ -WINPEDEF WINPE_EXPORT -INLINE void* STDCALL winpe_findmoduleaex( - PPEB peb, char *modulename); -#define winpe_findmodulea(modulename) winpe_findmoduleaex(NULL, modulename) - -/* - return LoadLibraryA func addr -*/ -WINPEDEF WINPE_EXPORT -INLINE PROC winpe_findloadlibrarya(); - -/* - return GetProcAddress func addr -*/ -WINPEDEF WINPE_EXPORT -INLINE PROC winpe_findgetprocaddress(); - -/* - find a valid space address start from imagebase with imagesize - use PFN_VirtualQuery for better use - return va with imagesize -*/ -WINPEDEF WINPE_EXPORT -INLINE void* STDCALL winpe_findspace( - size_t imagebase, size_t imagesize, size_t alignsize, - PFN_VirtualQuery pfnVirtualQuery); - -// PE load, adjust functions -/* - for overlay section in a pe file - return the overlay offset -*/ -WINPEDEF WINPE_EXPORT -INLINE size_t STDCALL winpe_overlayoffset(const void *rawpe); - -/* - load the origin rawpe in memory buffer by mem align - return memsize -*/ -WINPEDEF WINPE_EXPORT -INLINE size_t STDCALL winpe_memload( - const void *rawpe, size_t rawsize, - void *mempe, size_t memsize, - bool_t same_align); - -/* - realoc the addrs for the mempe addr as image base - origin image base usually at 0x00400000, 0x0000000180000000 - new image base mush be divided by 0x10000, if use loadlibrary - return realoc count -*/ -WINPEDEF WINPE_EXPORT -INLINE size_t STDCALL winpe_memreloc( - void *mempe, size_t newimagebase); - -/* - load the iat for the mempe, use rvafunc for winpe_memfindexp - return iat count -*/ -WINPEDEF WINPE_EXPORT -INLINE size_t STDCALL winpe_membindiat(void *mempe, - PFN_LoadLibraryA pfnLoadLibraryA, - PFN_GetProcAddress pfnGetProcAddress); - -/* - exec the tls callbacks for the mempe, before dll oep load - reason is for function PIMAGE_TLS_CALLBACK - return tls count -*/ -WINPEDEF WINPE_EXPORT -INLINE size_t STDCALL winpe_membindtls(void *mempe, DWORD reason); - -/* - find the iat addres, for call [iat] - return target iat va -*/ -WINPEDEF WINPE_EXPORT -INLINE void* STDCALL winpe_memfindiat(void *mempe, - LPCSTR dllname, LPCSTR funcname); - -/* - find the exp addres, the same as GetProcAddress - without forward to other dll - such as NTDLL.RtlInitializeSListHead - return target exp va -*/ -WINPEDEF WINPE_EXPORT -INLINE void* STDCALL winpe_memfindexp( - void *mempe, LPCSTR funcname); - - -WINPEDEF WINPE_EXPORT -INLINE void* STDCALL winpe_memfindexpcrc32( - void* mempe, uint32_t crc32); - -/* - forward the exp to the final expva - return the final exp va -*/ -WINPEDEF WINPE_EXPORT -INLINE void* STDCALL winpe_memforwardexp( - void *mempe, size_t exprva, - PFN_LoadLibraryA pfnLoadLibraryA, - PFN_GetProcAddress pfnGetProcAddress); - -// PE modify function -/* - change the oep of the pe if newoeprva!=0 - return the old oep rva -*/ -WINPEDEF WINPE_EXPORT -INLINE DWORD STDCALL winpe_oepval( - void *mempe, DWORD newoeprva); - -/* - change the imagebase of the pe if newimagebase!=0 - return the old imagebase va -*/ -WINPEDEF WINPE_EXPORT -INLINE size_t STDCALL winpe_imagebaseval( - void *mempe, size_t newimagebase); - -/* - change the imagesize of the pe if newimagesize!=0 - return the old imagesize -*/ -WINPEDEF WINPE_EXPORT -INLINE size_t STDCALL winpe_imagesizeval( - void *pe, size_t newimagesize); - -/* - close the aslr feature of an pe -*/ -WINPEDEF WINPE_EXPORT -INLINE void STDCALL winpe_noaslr(void *pe); - -/* - Append a section header in a pe, sect rva will be ignored - the mempe size must be enough for extend a section - return image size -*/ -WINPEDEF WINPE_EXPORT -INLINE size_t STDCALL winpe_appendsecth( - void *mempe, PIMAGE_SECTION_HEADER psecth); - - -#ifdef __cplusplus -} -#endif - - -#ifdef WINPE_IMPLEMENTATION - -#ifndef _DEBUG -#ifndef NDEBUG -#define NDEBUG -#endif -#endif - -#if defined(__TINYC__) -#ifdef _WIN64 -#pragma pack(8) -#else -#pragma pack(4) -#endif -#endif - -#include -#include -#include -#include - -// util INLINE functions -INLINE size_t _winpeinl_strlen(const char* str1) -{ - const char* p = str1; - while(*p) p++; - return p - str1; -} - -INLINE int _winpeinl_stricmp(const char *str1, const char *str2) -{ - int i=0; - while(str1[i]!=0 && str2[i]!=0) - { - if (str1[i] == str2[i] - || str1[i] + 0x20 == str2[i] - || str2[i] + 0x20 == str1[i]) - { - i++; - } - else - { - return (int)str1[i] - (int)str2[i]; - } - } - return (int)str1[i] - (int)str2[i]; -} - -INLINE int _winpeinl_stricmp2(const char *str1, const wchar_t* str2) -{ - int i=0; - while(str1[i]!=0 && str2[i]!=0) - { - if ((wchar_t)str1[i] == str2[i] - || (wchar_t)str1[i] + 0x20 == str2[i] - || str2[i] + 0x20 == (wchar_t)str1[i]) - { - i++; - } - else - { - return (int)str1[i] - (int)str2[i]; - } - } - return (int)str1[i] - (int)str2[i]; -} - -INLINE uint32_t _winpeinl_crc32(const void *buf, size_t n) -{ - uint32_t crc32 = ~0; - for(size_t i=0; i< n; i++) - { - crc32 ^= *(const uint8_t*)((uint8_t*)buf+i); - - for(int i = 0; i < 8; i++) - { - uint32_t t = ~((crc32&1) - 1); - crc32 = (crc32>>1) ^ (0xEDB88320 & t); - } - } - return ~crc32; -} - -INLINE void* _winpeinl_memset(void *buf, int ch, size_t n) -{ - char *p = buf; - for(size_t i=0;i0) - { - overlay = malloc(*poverlaysize); - memcpy(overlay, (uint8_t*)rawpe+overlayoffset, *poverlaysize); - } - } - free(rawpe); - return overlay; -} - -WINPEDEF WINPE_EXPORT -INLINE void* STDCALL winpe_memLoadLibrary(void *mempe) -{ - PFN_LoadLibraryA pfnLoadLibraryA = - (PFN_LoadLibraryA)winpe_findloadlibrarya(); - PFN_GetProcAddress pfnGetProcAddress = - (PFN_GetProcAddress)winpe_findgetprocaddress(); - return winpe_memLoadLibraryEx(mempe, 0, - WINPE_LDFLAG_MEMFIND | WINPE_LDFLAG_MEMALLOC, - pfnLoadLibraryA, pfnGetProcAddress); -} - -WINPEDEF WINPE_EXPORT -INLINE void* STDCALL winpe_memLoadLibraryEx(void *mempe, - size_t imagebase, DWORD flag, - PFN_LoadLibraryA pfnLoadLibraryA, - PFN_GetProcAddress pfnGetProcAddress) -{ - // bind windows api - char name_kernel32[] = { 'k', 'e', 'r', 'n', 'e', 'l', '3', '2', '.', 'd', 'l', 'l' , '\0'}; - char name_VirtualQuery[] = {'V', 'i', 'r', 't', 'u', 'a', 'l', 'Q', 'u', 'e', 'r', 'y', '\0'}; - char name_VirtualAlloc[] = {'V', 'i', 'r', 't', 'u', 'a', 'l', 'A', 'l', 'l', 'o', 'c', '\0'}; - char name_VirtualProtect[] = {'V', 'i', 'r', 't', 'u', 'a', 'l', 'P', 'r', 'o', 't', 'e', 'c', 't', '\0'}; - HMODULE hmod_kernel32 = pfnLoadLibraryA(name_kernel32); - PFN_VirtualQuery pfnVirtualQuery = (PFN_VirtualQuery) - pfnGetProcAddress(hmod_kernel32, name_VirtualQuery); - PFN_VirtualAlloc pfnVirtualAlloc = (PFN_VirtualAlloc) - pfnGetProcAddress(hmod_kernel32, name_VirtualAlloc); - PFN_VirtualProtect pfnVirtualProtect =(PFN_VirtualProtect) - pfnGetProcAddress(hmod_kernel32, name_VirtualProtect); - assert(pfnVirtualQuery!=0 && pfnVirtualAlloc!=0 && pfnVirtualProtect!=0); - - // find proper imagebase - size_t imagesize = winpe_imagesizeval(mempe, 0); - if(flag & WINPE_LDFLAG_MEMFIND) - { - imagebase = winpe_imagebaseval(mempe, 0); - imagebase = (size_t)winpe_findspace(imagebase, - imagesize, 0x10000, pfnVirtualQuery); - } - if(flag & WINPE_LDFLAG_MEMALLOC) // find proper memory to reloc - { - - imagebase = (size_t)pfnVirtualAlloc((void*)imagebase, - imagesize, MEM_COMMIT | MEM_RESERVE, - PAGE_EXECUTE_READWRITE); - if(!imagebase) // try alloc in arbitary place - { - imagebase = (size_t)pfnVirtualAlloc(NULL, - imagesize, MEM_COMMIT, - PAGE_EXECUTE_READWRITE); - if(!imagebase) return NULL; - } - else - { - imagebase = (size_t)pfnVirtualAlloc((void*)imagebase, - imagesize, MEM_COMMIT, PAGE_EXECUTE_READWRITE); - if(!imagebase) return NULL; - } - } - - // copy to imagebase - if(!imagebase) - { - imagebase = (size_t)mempe; - } - else - { - DWORD oldprotect; - pfnVirtualProtect((void*)imagebase, imagesize, - PAGE_EXECUTE_READWRITE, &oldprotect); - _winpeinl_memcpy((void*)imagebase, mempe, imagesize); - pfnVirtualProtect((void*)imagebase, imagesize, - oldprotect, &oldprotect); - } - - // initial memory module - if(!winpe_memreloc((void*)imagebase, imagebase)) - return NULL; - if(!winpe_membindiat((void*)imagebase, - pfnLoadLibraryA, pfnGetProcAddress)) return NULL; - winpe_membindtls(mempe, DLL_PROCESS_ATTACH); - PFN_DllMain pfnDllMain = (PFN_DllMain) - (imagebase + winpe_oepval((void*)imagebase, 0)); - pfnDllMain((HINSTANCE)imagebase, DLL_PROCESS_ATTACH, NULL); - return (void*)imagebase; -} - -WINPEDEF WINPE_EXPORT -INLINE BOOL STDCALL winpe_memFreeLibrary(void *mempe) -{ - PFN_LoadLibraryA pfnLoadLibraryA = - (PFN_LoadLibraryA)winpe_findloadlibrarya(); - PFN_GetProcAddress pfnGetProcAddress = - (PFN_GetProcAddress)winpe_findgetprocaddress(); - return winpe_memFreeLibraryEx(mempe, - pfnLoadLibraryA, pfnGetProcAddress); -} - -WINPEDEF WINPE_EXPORT -INLINE BOOL STDCALL winpe_memFreeLibraryEx(void *mempe, - PFN_LoadLibraryA pfnLoadLibraryA, - PFN_GetProcAddress pfnGetProcAddress) -{ - char name_kernel32[] = {'k', 'e', 'r', 'n', 'e', 'l', '3', '2', '\0'}; - char name_VirtualFree[] = {'V', 'i', 'r', 't', 'u', 'a', 'l', 'F', 'r', 'e', 'e', '\0'}; - HMODULE hmod_kernel32 = pfnLoadLibraryA(name_kernel32); - PFN_VirtualFree pfnVirtualFree = (PFN_VirtualFree) - pfnGetProcAddress(hmod_kernel32, name_VirtualFree); - PFN_DllMain pfnDllMain = (PFN_DllMain) - ((uint8_t*)mempe + winpe_oepval(mempe, 0)); - winpe_membindtls(mempe, DLL_PROCESS_DETACH); - pfnDllMain((HINSTANCE)mempe, DLL_PROCESS_DETACH, NULL); - return pfnVirtualFree(mempe, 0, MEM_FREE); -} - -WINPEDEF WINPE_EXPORT -INLINE PROC STDCALL winpe_memGetProcAddress( - void *mempe, const char *funcname) -{ - void* expva = winpe_memfindexp(mempe, funcname); - size_t exprva = (size_t)((uint8_t*)expva - (uint8_t*)mempe); - return (PROC)winpe_memforwardexp(mempe, exprva, // to avoid infinity loop - (PFN_LoadLibraryA)winpe_findloadlibrarya(), - (PFN_GetProcAddress)winpe_findgetprocaddress()); -} - -// PE query functions -WINPEDEF WINPE_EXPORT -INLINE void* winpe_findkernel32() -{ - // return (void*)LoadLibrary("kernel32.dll"); - // TEB->PEB->Ldr->InMemoryOrderLoadList->curProgram->ntdll->kernel32 - void *kerenl32 = NULL; - -#ifndef WINPE_NOASM -#ifdef _WIN64 - __asm{ - mov rax, gs:[60h]; peb - mov rax, [rax+18h]; ldr - mov rax, [rax+20h]; InMemoryOrderLoadList, currentProgramEntry - mov rax, [rax]; ntdllEntry, currentProgramEntry->->Flink - mov rax, [rax]; kernel32Entry, ntdllEntry->Flink - mov rax, [rax-10h+30h]; kernel32.DllBase - mov kerenl32, rax; - } -#else - __asm{ - mov eax, fs:[30h]; peb - mov eax, [eax+0ch]; ldr - mov eax, [eax+14h]; InMemoryOrderLoadList, currentProgramEntry - mov eax, [eax]; ntdllEntry, currentProgramEntry->->Flink - mov eax, [eax]; kernel32Entry, ntdllEntry->Flink - mov eax, [eax - 8h +18h]; kernel32.DllBase - mov kerenl32, eax; - } -#endif -#else - char name_kernel32[] = { 'k', 'e', 'r', 'n', 'e', 'l', '3', '2', '.', 'd', 'l', 'l' , '\0' }; - kerenl32 = winpe_findmodulea(name_kernel32); -#endif - - return kerenl32; -} - -WINPEDEF WINPE_EXPORT -INLINE void* STDCALL winpe_findmoduleaex( - PPEB peb, char *modulename) -{ - typedef struct _LDR_ENTRY // has 3 kinds of pointer link list - { - LIST_ENTRY InLoadOrderLinks; // this has link pointer - LIST_ENTRY InMemoryOrderLinks; // order is program, ntdll, kernel32.dll - LIST_ENTRY InInitializationOrderLinks;//to next entry in same place - PVOID DllBase; // 0x18, 0x30 - PVOID EntryPoint; - ULONG SizeOfImage; - UNICODE_STRING FullDllName; - UNICODE_STRING BaseDllName; - ULONG Flags; - USHORT LoadCount; - USHORT TlsIndex; - union - { - LIST_ENTRY HashLinks; - struct - { - PVOID SectionPointer; - ULONG CheckSum; - }; - }; - ULONG TimeDateStamp; - } LDR_ENTRY, *PLDR_ENTRY; // use this because of mingw bug - - PLDR_ENTRY ldrentry = NULL; - PPEB_LDR_DATA ldr = NULL; - - - if(!peb) - { - PTEB teb = NtCurrentTeb(); -#ifdef _WIN64 - peb = *(PPEB*)((uint8_t*)teb + 0x60); -#else - peb = *(PPEB*)((uint8_t*)teb + 0x30); -#endif - } - -#ifdef _WIN64 - ldr = *(PPEB_LDR_DATA*)((uint8_t*)peb + 0x18); -#else - ldr = *(PPEB_LDR_DATA*)((uint8_t*)peb + 0xC); -#endif - - // InMemoryOrderModuleList is the second entry - ldrentry = (PLDR_ENTRY)((size_t) - ldr->InMemoryOrderModuleList.Flink - 2*sizeof(size_t)); - if(!modulename) - { - return ldrentry->DllBase; - } - while(ldrentry->InMemoryOrderLinks.Flink != - ldr->InMemoryOrderModuleList.Flink) - { - PUNICODE_STRING ustr = &ldrentry->FullDllName; - int i; - for(i=ustr->Length/2-1; i>0 && ustr->Buffer[i]!='\\';i--); - if(ustr->Buffer[i]=='\\') i++; - if(_winpeinl_stricmp2(modulename, ustr->Buffer + i)==0) - { - return ldrentry->DllBase; - } - ldrentry = (PLDR_ENTRY)((size_t) - ldrentry->InMemoryOrderLinks.Flink - 2*sizeof(size_t)); - } - return NULL; -} - -WINPEDEF WINPE_EXPORT -INLINE PROC winpe_findloadlibrarya() -{ - // return (PROC)LoadLibraryA; - HMODULE hmod_kernel32 = (HMODULE)winpe_findkernel32(); - char name_LoadLibraryA[] = {'L', 'o', 'a', 'd', 'L', 'i', 'b', 'r', 'a', 'r', 'y', 'A', '\0'}; - return (PROC)winpe_memfindexp( // suppose exp no forward, to avoid recursive - (void*)hmod_kernel32, name_LoadLibraryA); -} - -WINPEDEF WINPE_EXPORT -INLINE PROC winpe_findgetprocaddress() -{ - // return (PROC)GetProcAddress; - HMODULE hmod_kernel32 = (HMODULE)winpe_findkernel32(); - char name_GetProcAddress[] = {'G', 'e', 't', 'P', 'r', 'o', 'c', 'A', 'd', 'd', 'r', 'e', 's', 's', '\0'}; - return (PROC)winpe_memfindexp(hmod_kernel32, name_GetProcAddress); -} - -WINPEDEF WINPE_EXPORT -INLINE void* STDCALL winpe_findspace( - size_t imagebase, size_t imagesize, size_t alignsize, - PFN_VirtualQuery pfnVirtualQuery) -{ -#define MAX_QUERY 0x1000 - size_t addr = imagebase; - MEMORY_BASIC_INFORMATION minfo; - for (int i=0;i= imagesize) - return (void*)addr; - addr += minfo.RegionSize; - } - return NULL; -} - -// PE load, adjust functions -WINPEDEF WINPE_EXPORT -INLINE size_t STDCALL winpe_overlayoffset(const void *rawpe) -{ - PIMAGE_DOS_HEADER pDosHeader = (PIMAGE_DOS_HEADER)rawpe; - PIMAGE_NT_HEADERS pNtHeader = (PIMAGE_NT_HEADERS) - ((uint8_t*)rawpe + pDosHeader->e_lfanew); - PIMAGE_FILE_HEADER pFileHeader = &pNtHeader->FileHeader; - PIMAGE_OPTIONAL_HEADER pOptHeader = &pNtHeader->OptionalHeader; - PIMAGE_DATA_DIRECTORY pDataDirectory = pOptHeader->DataDirectory; - PIMAGE_SECTION_HEADER pSectHeader = (PIMAGE_SECTION_HEADER) - ((uint8_t*)pOptHeader + pFileHeader->SizeOfOptionalHeader); - WORD sectNum = pFileHeader->NumberOfSections; - - return pSectHeader[sectNum-1].PointerToRawData + - pSectHeader[sectNum-1].SizeOfRawData; -} - -WINPEDEF WINPE_EXPORT -INLINE size_t STDCALL winpe_memload( - const void *rawpe, size_t rawsize, - void *mempe, size_t memsize, - bool_t same_align) -{ - // load rawpe to memalign - PIMAGE_DOS_HEADER pDosHeader = (PIMAGE_DOS_HEADER)rawpe; - PIMAGE_NT_HEADERS pNtHeader = (PIMAGE_NT_HEADERS) - ((uint8_t*)rawpe + pDosHeader->e_lfanew); - PIMAGE_FILE_HEADER pFileHeader = &pNtHeader->FileHeader; - PIMAGE_OPTIONAL_HEADER pOptHeader = &pNtHeader->OptionalHeader; - PIMAGE_SECTION_HEADER pSectHeader = (PIMAGE_SECTION_HEADER) - ((uint8_t*)pOptHeader + pFileHeader->SizeOfOptionalHeader); - WORD sectNum = pFileHeader->NumberOfSections; - size_t imagesize = pOptHeader->SizeOfImage; - if(!mempe) return imagesize; - else if(memsize!=0 && memsizeSizeOfHeaders); - - for(WORD i=0;ie_lfanew); - pFileHeader = &pNtHeader->FileHeader; - pOptHeader = &pNtHeader->OptionalHeader; - pSectHeader = (PIMAGE_SECTION_HEADER) - ((uint8_t*)pOptHeader + pFileHeader->SizeOfOptionalHeader); - sectNum = pFileHeader->NumberOfSections; - - pOptHeader->FileAlignment = pOptHeader->SectionAlignment; - - for(WORD i=0;ie_lfanew); - PIMAGE_FILE_HEADER pFileHeader = &pNtHeader->FileHeader; - PIMAGE_OPTIONAL_HEADER pOptHeader = &pNtHeader->OptionalHeader; - PIMAGE_DATA_DIRECTORY pDataDirectory = pOptHeader->DataDirectory; - PIMAGE_DATA_DIRECTORY pRelocEntry = &pDataDirectory[IMAGE_DIRECTORY_ENTRY_BASERELOC]; - - DWORD reloc_count = 0; - DWORD reloc_offset = 0; - int64_t shift = (int64_t)newimagebase - - (int64_t)pOptHeader->ImageBase; - while (reloc_offset < pRelocEntry->Size) - { - PIMAGE_BASE_RELOCATION pBaseReloc = (PIMAGE_BASE_RELOCATION) - ((uint8_t*)mempe + pRelocEntry->VirtualAddress + reloc_offset); - PRELOCOFFSET pRelocOffset = (PRELOCOFFSET)((uint8_t*)pBaseReloc - + sizeof(IMAGE_BASE_RELOCATION)); - DWORD item_num = (pBaseReloc->SizeOfBlock - // RELOCOFFSET block num - sizeof(IMAGE_BASE_RELOCATION)) / sizeof(RELOCOFFSET); - for (size_t i = 0; i < item_num; i++) - { - if (!pRelocOffset[i].type && - !pRelocOffset[i].offset) continue; - DWORD targetoffset = pBaseReloc->VirtualAddress + - pRelocOffset[i].offset; - size_t *paddr = (size_t *)((uint8_t*)mempe + targetoffset); - size_t relocaddr = (size_t)((int64_t)*paddr + shift); - //printf("reloc 0x%08x->0x%08x\n", *paddr, relocaddr); - *paddr = relocaddr; - } - reloc_offset += sizeof(IMAGE_BASE_RELOCATION) + - sizeof(RELOCOFFSET) * item_num; - reloc_count += item_num; - } - pOptHeader->ImageBase = newimagebase; - return reloc_count; -} - -WINPEDEF WINPE_EXPORT -INLINE size_t STDCALL winpe_membindiat(void *mempe, - PFN_LoadLibraryA pfnLoadLibraryA, - PFN_GetProcAddress pfnGetProcAddress) -{ - PIMAGE_DOS_HEADER pDosHeader = (PIMAGE_DOS_HEADER)mempe; - PIMAGE_NT_HEADERS pNtHeader = (PIMAGE_NT_HEADERS) - ((uint8_t*)mempe + pDosHeader->e_lfanew); - PIMAGE_FILE_HEADER pFileHeader = &pNtHeader->FileHeader; - PIMAGE_OPTIONAL_HEADER pOptHeader = &pNtHeader->OptionalHeader; - PIMAGE_DATA_DIRECTORY pDataDirectory = pOptHeader->DataDirectory; - PIMAGE_DATA_DIRECTORY pImpEntry = - &pDataDirectory[IMAGE_DIRECTORY_ENTRY_IMPORT]; - PIMAGE_IMPORT_DESCRIPTOR pImpDescriptor = - (PIMAGE_IMPORT_DESCRIPTOR)((uint8_t*)mempe + pImpEntry->VirtualAddress); - - PIMAGE_THUNK_DATA pFtThunk = NULL; - PIMAGE_THUNK_DATA pOftThunk = NULL; - LPCSTR pDllName = NULL; - PIMAGE_IMPORT_BY_NAME pImpByName = NULL; - size_t funcva = 0; - char *funcname = NULL; - - // origin GetProcAddress will crash at InitializeSListHead - if(!pfnLoadLibraryA) pfnLoadLibraryA = - (PFN_LoadLibraryA)winpe_findloadlibrarya(); - if(!pfnGetProcAddress) pfnGetProcAddress = - (PFN_GetProcAddress)winpe_findgetprocaddress(); - - DWORD iat_count = 0; - for (; pImpDescriptor->Name; pImpDescriptor++) - { - pDllName = (LPCSTR)((uint8_t*)mempe + pImpDescriptor->Name); - pFtThunk = (PIMAGE_THUNK_DATA) - ((uint8_t*)mempe + pImpDescriptor->FirstThunk); - pOftThunk = (PIMAGE_THUNK_DATA) - ((uint8_t*)mempe + pImpDescriptor->OriginalFirstThunk); - size_t dllbase = (size_t)pfnLoadLibraryA(pDllName); - if(!dllbase) return 0; - - for (int j=0; pFtThunk[j].u1.Function - && pOftThunk[j].u1.Function; j++) - { - size_t _addr = (size_t)((uint8_t*)mempe + pOftThunk[j].u1.AddressOfData); - if(sizeof(size_t)>4) // x64 - { - if(((uint64_t)_addr>>63) == 1) - { - funcname = (char *)(_addr & 0x000000000000ffff); - } - else - { - pImpByName=(PIMAGE_IMPORT_BY_NAME)_addr; - funcname = pImpByName->Name; - } - } - else - { - if(((size_t)pImpByName>>31) == 1) - { - funcname = (char *)(_addr & 0x0000ffff); - } - else - { - pImpByName=(PIMAGE_IMPORT_BY_NAME)_addr; - funcname = pImpByName->Name; - } - } - - funcva = (size_t)pfnGetProcAddress( - (HMODULE)dllbase, funcname); - if(!funcva) continue; - pFtThunk[j].u1.Function = funcva; - assert(funcva == (size_t)GetProcAddress( - (HMODULE)dllbase, funcname)); - iat_count++; - } - } - return iat_count; -} - -WINPEDEF WINPE_EXPORT -INLINE size_t STDCALL winpe_membindtls(void *mempe, DWORD reason) -{ - PIMAGE_DOS_HEADER pDosHeader = (PIMAGE_DOS_HEADER)mempe; - PIMAGE_NT_HEADERS pNtHeader = (PIMAGE_NT_HEADERS) - ((uint8_t*)mempe + pDosHeader->e_lfanew); - PIMAGE_FILE_HEADER pFileHeader = &pNtHeader->FileHeader; - PIMAGE_OPTIONAL_HEADER pOptHeader = &pNtHeader->OptionalHeader; - PIMAGE_DATA_DIRECTORY pDataDirectory = pOptHeader->DataDirectory; - PIMAGE_DATA_DIRECTORY pTlsDirectory = - &pDataDirectory[IMAGE_DIRECTORY_ENTRY_TLS]; - if(!pTlsDirectory->VirtualAddress) return 0; - - size_t tls_count = 0; - PIMAGE_TLS_DIRECTORY pTlsEntry = (PIMAGE_TLS_DIRECTORY) - ((uint8_t*)mempe + pTlsDirectory->VirtualAddress); - PIMAGE_TLS_CALLBACK *tlscb= (PIMAGE_TLS_CALLBACK*) - pTlsEntry->AddressOfCallBacks; - if(tlscb) - { - while(*tlscb) - { - (*tlscb)(mempe, reason, NULL); - tlscb++; - tls_count++; - } - } - return tls_count; -} - -WINPEDEF WINPE_EXPORT -INLINE void* STDCALL winpe_memfindiat(void *mempe, - LPCSTR dllname, LPCSTR funcname) -{ - PIMAGE_DOS_HEADER pDosHeader = (PIMAGE_DOS_HEADER)mempe; - PIMAGE_NT_HEADERS pNtHeader = (PIMAGE_NT_HEADERS) - ((uint8_t*)mempe + pDosHeader->e_lfanew); - PIMAGE_FILE_HEADER pFileHeader = &pNtHeader->FileHeader; - PIMAGE_OPTIONAL_HEADER pOptHeader = &pNtHeader->OptionalHeader; - PIMAGE_DATA_DIRECTORY pDataDirectory = pOptHeader->DataDirectory; - PIMAGE_DATA_DIRECTORY pImpEntry = - &pDataDirectory[IMAGE_DIRECTORY_ENTRY_IMPORT]; - PIMAGE_IMPORT_DESCRIPTOR pImpDescriptor = - (PIMAGE_IMPORT_DESCRIPTOR)((uint8_t*)mempe + pImpEntry->VirtualAddress); - - PIMAGE_THUNK_DATA pFtThunk = NULL; - PIMAGE_THUNK_DATA pOftThunk = NULL; - LPCSTR pDllName = NULL; - PIMAGE_IMPORT_BY_NAME pImpByName = NULL; - - for (; pImpDescriptor->Name; pImpDescriptor++) - { - pDllName = (LPCSTR)((uint8_t*)mempe + pImpDescriptor->Name); - if(dllname && _winpeinl_stricmp(pDllName, dllname)!=0) continue; - pFtThunk = (PIMAGE_THUNK_DATA) - ((uint8_t*)mempe + pImpDescriptor->FirstThunk); - pOftThunk = (PIMAGE_THUNK_DATA) - ((uint8_t*)mempe + pImpDescriptor->OriginalFirstThunk); - - for (int j=0; pFtThunk[j].u1.Function - && pOftThunk[j].u1.Function; j++) - { - pImpByName=(PIMAGE_IMPORT_BY_NAME)((uint8_t*)mempe + - pOftThunk[j].u1.AddressOfData); - if((size_t)funcname < MAXWORD) // ordinary - { - WORD funcord = LOWORD(funcname); - if(pImpByName->Hint == funcord) - return &pFtThunk[j]; - } - else - { - if(_winpeinl_stricmp(pImpByName->Name, funcname)==0) - return &pFtThunk[j]; - } - } - } - return 0; -} - -WINPEDEF WINPE_EXPORT -INLINE void* STDCALL winpe_memfindexp( - void *mempe, LPCSTR funcname) -{ - PIMAGE_DOS_HEADER pDosHeader = (PIMAGE_DOS_HEADER)mempe; - PIMAGE_NT_HEADERS pNtHeader = (PIMAGE_NT_HEADERS) - ((uint8_t*)mempe + pDosHeader->e_lfanew); - PIMAGE_FILE_HEADER pFileHeader = &pNtHeader->FileHeader; - PIMAGE_OPTIONAL_HEADER pOptHeader = &pNtHeader->OptionalHeader; - PIMAGE_DATA_DIRECTORY pDataDirectory = pOptHeader->DataDirectory; - PIMAGE_DATA_DIRECTORY pExpEntry = - &pDataDirectory[IMAGE_DIRECTORY_ENTRY_EXPORT]; - PIMAGE_EXPORT_DIRECTORY pExpDescriptor = - (PIMAGE_EXPORT_DIRECTORY)((uint8_t*)mempe + pExpEntry->VirtualAddress); - - WORD *ordrva = (WORD*)((uint8_t*)mempe - + pExpDescriptor->AddressOfNameOrdinals); - DWORD *namerva = (DWORD*)((uint8_t*)mempe - + pExpDescriptor->AddressOfNames); - DWORD *funcrva = (DWORD*)((uint8_t*)mempe - + pExpDescriptor->AddressOfFunctions); - if((size_t)funcname <= MAXWORD) // find by ordnial - { - WORD ordbase = LOWORD(pExpDescriptor->Base) - 1; - WORD funcord = LOWORD(funcname); - return (void*)((uint8_t*)mempe + funcrva[ordrva[funcord-ordbase]]); - } - else - { - for(DWORD i=0;iNumberOfNames;i++) - { - LPCSTR curname = (LPCSTR)((uint8_t*)mempe+namerva[i]); - if(_winpeinl_stricmp(curname, funcname)==0) - { - return (void*)((uint8_t*)mempe + funcrva[ordrva[i]]); - } - } - } - return NULL; -} - -WINPEDEF WINPE_EXPORT -INLINE void* STDCALL winpe_memfindexpcrc32( - void* mempe, uint32_t crc32) -{ - PIMAGE_DOS_HEADER pDosHeader = (PIMAGE_DOS_HEADER)mempe; - PIMAGE_NT_HEADERS pNtHeader = (PIMAGE_NT_HEADERS) - ((uint8_t*)mempe + pDosHeader->e_lfanew); - PIMAGE_FILE_HEADER pFileHeader = &pNtHeader->FileHeader; - PIMAGE_OPTIONAL_HEADER pOptHeader = &pNtHeader->OptionalHeader; - PIMAGE_DATA_DIRECTORY pDataDirectory = pOptHeader->DataDirectory; - PIMAGE_DATA_DIRECTORY pExpEntry = - &pDataDirectory[IMAGE_DIRECTORY_ENTRY_EXPORT]; - PIMAGE_EXPORT_DIRECTORY pExpDescriptor = - (PIMAGE_EXPORT_DIRECTORY)((uint8_t*)mempe + pExpEntry->VirtualAddress); - - WORD* ordrva = (WORD*)((uint8_t*)mempe - + pExpDescriptor->AddressOfNameOrdinals); - DWORD* namerva = (DWORD*)((uint8_t*)mempe - + pExpDescriptor->AddressOfNames); - DWORD* funcrva = (DWORD*)((uint8_t*)mempe - + pExpDescriptor->AddressOfFunctions); - for (DWORD i = 0; i < pExpDescriptor->NumberOfNames; i++) - { - LPCSTR curname = (LPCSTR)((uint8_t*)mempe + namerva[i]); - if (crc32==_winpeinl_crc32(curname, _winpeinl_strlen(curname))) - { - return (void*)((uint8_t*)mempe + funcrva[ordrva[i]]); - } - } - return NULL; -} - -WINPEDEF WINPE_EXPORT -INLINE void* STDCALL winpe_memforwardexp( - void *mempe, size_t exprva, - PFN_LoadLibraryA pfnLoadLibraryA, - PFN_GetProcAddress pfnGetProcAddress) -{ - // this function might have infinite loop - // such as this situation - // kerenl32.dll, GetProcessMitigationPolicy -> api-ms-win-core-processthreads-l1-1-1.dll -> kerenl32.dll, GetProcessMitigationPolicys - size_t dllbase = (size_t)mempe; - while (1) - { - PIMAGE_DOS_HEADER pDosHeader = (PIMAGE_DOS_HEADER)dllbase; - PIMAGE_NT_HEADERS pNtHeader = (PIMAGE_NT_HEADERS) - ((uint8_t*)dllbase + pDosHeader->e_lfanew); - PIMAGE_OPTIONAL_HEADER pOptHeader = &pNtHeader->OptionalHeader; - PIMAGE_DATA_DIRECTORY pDataDirectory = pOptHeader->DataDirectory; - PIMAGE_DATA_DIRECTORY pExpEntry = - &pDataDirectory[IMAGE_DIRECTORY_ENTRY_EXPORT]; - if(exprva>=pExpEntry->VirtualAddress && - exprva<= pExpEntry->VirtualAddress + pExpEntry->Size) - { - char namebuf[MAX_PATH]; - char *dllname = (char *)(dllbase + exprva); - char *funcname = dllname; - int i=0, j=0; - while(dllname[i]!=0) - { - if(dllname[i]=='.') - { - namebuf[j] = dllname[i]; - namebuf[++j] = 'd'; - namebuf[++j] = 'l'; - namebuf[++j] = 'l'; - namebuf[++j] = '\0'; - funcname = namebuf + j + 1; - } - else - { - namebuf[j]=dllname[i]; - } - i++; - j++; - } - namebuf[j] = '\0'; - dllname = namebuf; - dllbase = (size_t)pfnLoadLibraryA(dllname); - exprva = (size_t)pfnGetProcAddress((HMODULE)dllbase, funcname); - exprva -= dllbase; - } - else - { - return (void*)(dllbase + exprva); - } - } - return NULL; -} - -// PE setting function -WINPEDEF WINPE_EXPORT -INLINE void STDCALL winpe_noaslr(void *pe) -{ - PIMAGE_DOS_HEADER pDosHeader = (PIMAGE_DOS_HEADER)pe; - PIMAGE_NT_HEADERS pNtHeader = (PIMAGE_NT_HEADERS) - ((uint8_t*)pe + pDosHeader->e_lfanew); - PIMAGE_FILE_HEADER pFileHeader = &pNtHeader->FileHeader; - PIMAGE_OPTIONAL_HEADER pOptHeader = &pNtHeader->OptionalHeader; - #ifndef IMAGE_DLLCHARACTERISTICS_DYNAMIC_BASE - #define IMAGE_DLLCHARACTERISTICS_DYNAMIC_BASE 0x0040 - #endif - pOptHeader->DllCharacteristics &= ~IMAGE_DLLCHARACTERISTICS_DYNAMIC_BASE; -} - -WINPEDEF WINPE_EXPORT -INLINE DWORD STDCALL winpe_oepval(void *pe, DWORD newoeprva) -{ - PIMAGE_DOS_HEADER pDosHeader = (PIMAGE_DOS_HEADER)pe; - PIMAGE_NT_HEADERS pNtHeader = (PIMAGE_NT_HEADERS) - ((uint8_t*)pe + pDosHeader->e_lfanew); - PIMAGE_FILE_HEADER pFileHeader = &pNtHeader->FileHeader; - PIMAGE_OPTIONAL_HEADER pOptHeader = &pNtHeader->OptionalHeader; - DWORD orgoep = pOptHeader->AddressOfEntryPoint; - if(newoeprva) pOptHeader->AddressOfEntryPoint = newoeprva; - return orgoep; -} - -WINPEDEF WINPE_EXPORT -INLINE size_t STDCALL winpe_imagebaseval(void *pe, size_t newimagebase) -{ - PIMAGE_DOS_HEADER pDosHeader = (PIMAGE_DOS_HEADER)pe; - PIMAGE_NT_HEADERS pNtHeader = (PIMAGE_NT_HEADERS) - ((uint8_t*)pe + pDosHeader->e_lfanew); - PIMAGE_FILE_HEADER pFileHeader = &pNtHeader->FileHeader; - PIMAGE_OPTIONAL_HEADER pOptHeader = &pNtHeader->OptionalHeader; - size_t imagebase = pOptHeader->ImageBase; - if(newimagebase) pOptHeader->ImageBase = newimagebase; - return imagebase; -} - -WINPEDEF WINPE_EXPORT -INLINE size_t STDCALL winpe_imagesizeval(void *pe, size_t newimagesize) -{ - PIMAGE_DOS_HEADER pDosHeader = (PIMAGE_DOS_HEADER)pe; - PIMAGE_NT_HEADERS pNtHeader = (PIMAGE_NT_HEADERS) - ((uint8_t*)pe + pDosHeader->e_lfanew); - PIMAGE_FILE_HEADER pFileHeader = &pNtHeader->FileHeader; - PIMAGE_OPTIONAL_HEADER pOptHeader = &pNtHeader->OptionalHeader; - size_t imagesize = pOptHeader->SizeOfImage; - if(newimagesize) pOptHeader->SizeOfImage = (DWORD)newimagesize; - return imagesize; -} - -WINPEDEF WINPE_EXPORT -INLINE size_t STDCALL winpe_appendsecth(void *pe, - PIMAGE_SECTION_HEADER psecth) -{ - PIMAGE_DOS_HEADER pDosHeader = (PIMAGE_DOS_HEADER)pe; - PIMAGE_NT_HEADERS pNtHeader = (PIMAGE_NT_HEADERS) - ((uint8_t*)pe + pDosHeader->e_lfanew); - PIMAGE_FILE_HEADER pFileHeader = &pNtHeader->FileHeader; - PIMAGE_OPTIONAL_HEADER pOptHeader = &pNtHeader->OptionalHeader; - PIMAGE_SECTION_HEADER pSectHeader = (PIMAGE_SECTION_HEADER) - ((uint8_t*)pOptHeader + pFileHeader->SizeOfOptionalHeader); - WORD sectNum = pFileHeader->NumberOfSections; - PIMAGE_SECTION_HEADER pLastSectHeader = &pSectHeader[sectNum-1]; - DWORD addr, align; - - // check the space to append section - if(pFileHeader->SizeOfOptionalHeader - + sizeof(IMAGE_SECTION_HEADER) - > pSectHeader[0].PointerToRawData) return 0; - - // fill rva addr - align = pOptHeader->SectionAlignment; - addr = pLastSectHeader->VirtualAddress + pLastSectHeader->Misc.VirtualSize; - if(addr % align) addr += align - addr%align; - psecth->VirtualAddress = addr; - - // fill file offset - align = pOptHeader->FileAlignment; - addr = pLastSectHeader->PointerToRawData+ pLastSectHeader->SizeOfRawData; - if(addr % align) addr += align - addr%align; - psecth->PointerToRawData = addr; - - // adjust the section and imagesize - pFileHeader->NumberOfSections++; - _winpeinl_memcpy(&pSectHeader[sectNum], psecth, sizeof(IMAGE_SECTION_HEADER)); - align = pOptHeader->SectionAlignment; - addr = psecth->VirtualAddress + psecth->Misc.VirtualSize; - if(addr % align) addr += align - addr%align; - pOptHeader->SizeOfImage = addr; - return pOptHeader->SizeOfImage; -} - -#endif -#endif - -/* -history: -v0.1, initial version, with load pe in memory align -V0.1.2, adjust declear name, load pe iat -v0.2, add append section, findiat function -v0.2.2, add function winpe_memfindexp -v0.2.5, INLINE basic functions, better for shellcode -v0.3, add winpe_memloadlibrary, winpe_memGetprocaddress, winpe_memFreelibrary -v0.3.1, fix the stdcall function name by .def, load memory moudule aligned with 0x1000(x86), 0x10000(x64) -v0.3.2, x64 memory load support, winpe_findkernel32, winpe_finmodule by asm -v0.3.3, add ordinal support in winpe_membindiat, add win_membindtls, change all call to STDCALL -v0.3.4, add WINPE_NOASM to make compatible for vs x64 -v0.3.5, add winpe_memfindexpcrc32 +/* +This tool is for parsing windows pe structure, adjust realoc addrs, or iat. +Most functions are independent by INLINE all parts, +so that this can also be used as shellcode + v0.3.5, developed by devseed +*/ + +#ifndef _WINPE_H +#define _WINPE_H +#define WINPE_VERSION 350 + +#include +#include +#include + +#ifndef WINPEDEF +#ifdef WINPE_STATIC +#define WINPEDEF static +#else +#define WINPEDEF extern +#endif +#endif + +#ifndef WINPE_SHARED +#define WINPE_EXPORT +#else +#if defined(_WIN32) +#define WINPE_EXPORT __declspec(dllexport) +#else +#define WINPE_EXPORT __attribute__((visibility("default"))) +#endif +#endif + +#if defined(_WIN32) +#ifndef STDCALL +#define STDCALL __stdcall +#endif +#ifdef NAKED +#define NAKED __declspec(naked) +#endif +#else +#ifndef STDCALL +#define STDCALL __attribute__((stdcall)) +#endif +#ifdef NAKED +#define NAKED __attribute__((naked)) +#endif +#endif + +#ifndef INLINE +#if defined(_MSC_VER) +#define INLINE __forceinline +#else // tcc, gcc not support inline export, tcc inline will output nofunction ... +#define INLINE +#endif +#endif + +#ifdef __cplusplus +extern "C" { +#endif +typedef struct _RELOCOFFSET +{ + WORD offset : 12; + WORD type : 4; +}RELOCOFFSET,*PRELOCOFFSET; + +typedef int bool_t; + +typedef HMODULE (WINAPI *PFN_LoadLibraryA)( + LPCSTR lpLibFileName); + +typedef FARPROC (WINAPI *PFN_GetProcAddress)( + HMODULE hModule, LPCSTR lpProcName); + +typedef PFN_GetProcAddress PFN_GetProcRVA; + +typedef LPVOID (WINAPI *PFN_VirtualAlloc)( + LPVOID lpAddress, SIZE_T dwSize, + DWORD flAllocationType, DWORD flProtect); + +typedef BOOL (WINAPI *PFN_VirtualFree)( + LPVOID lpAddress, SIZE_T dwSize, + DWORD dwFreeType); + +typedef BOOL (WINAPI *PFN_VirtualProtect)( + LPVOID lpAddress, SIZE_T dwSize, + DWORD flNewProtect, PDWORD lpflOldProtect); + +typedef SIZE_T (WINAPI *PFN_VirtualQuery)( + LPCVOID lpAddress, + PMEMORY_BASIC_INFORMATION lpBuffer, + SIZE_T dwLength); + +typedef BOOL (WINAPI *PFN_DllMain)(HINSTANCE hinstDLL, + DWORD fdwReason, LPVOID lpReserved ); + +#define WINPE_LDFLAG_MEMALLOC 0x1 +#define WINPE_LDFLAG_MEMFIND 0x2 + +// PE high order fnctions +/* + load the origin rawpe file in memory buffer by mem align + mempe means the pe in memory alignment + return mempe buffer, memsize +*/ +WINPEDEF WINPE_EXPORT +void* STDCALL winpe_memload_file(const char *path, + size_t *pmemsize, bool_t same_align); + +/* + load the overlay data in a pe file + return overlay buf, overlay size +*/ +WINPEDEF WINPE_EXPORT +void* STDCALL winpe_overlayload_file(const char *path, + size_t *poverlaysize); + +/* + similar to LoadlibrayA, will call dllentry + will load the mempe in a valid imagebase + return hmodule base +*/ +WINPEDEF WINPE_EXPORT +INLINE void* STDCALL winpe_memLoadLibrary(void *mempe); + +/* + if imagebase==0, will load on mempe, or in imagebase + will load the mempe in a valid imagebase, flag as below: + WINPE_LDFLAG_MEMALLOC 0x1, will alloc memory to imagebase + WINPE_LDFLAG_MEMFIND 0x2, will find a valid space, + must combined with WINPE_LDFLAG_MEMALLOC + return hmodule base +*/ +WINPEDEF WINPE_EXPORT +INLINE void* STDCALL winpe_memLoadLibraryEx(void *mempe, + size_t imagebase, DWORD flag, + PFN_LoadLibraryA pfnLoadLibraryA, + PFN_GetProcAddress pfnGetProcAddress); + +/* + similar to FreeLibrary, will call dllentry + return true or false +*/ +WINPEDEF WINPE_EXPORT +INLINE BOOL STDCALL winpe_memFreeLibrary(void *mempe); + +/* + FreeLibraryEx with VirtualFree custom function + return true or false +*/ +WINPEDEF WINPE_EXPORT +INLINE BOOL STDCALL winpe_memFreeLibraryEx(void *mempe, + PFN_LoadLibraryA pfnLoadLibraryA, + PFN_GetProcAddress pfnGetProcAddress); + + +/* + similar to GetProcAddress + return function va +*/ +WINPEDEF WINPE_EXPORT +INLINE PROC STDCALL winpe_memGetProcAddress( + void *mempe, const char *funcname); + +// PE query functions +/* + use peb and ldr list, to obtain to find kernel32.dll address + return kernel32.dll address +*/ +WINPEDEF WINPE_EXPORT +INLINE void* winpe_findkernel32(); + +/* + use peb and ldr list, similar as GetModuleHandleA + return ldr module address +*/ +WINPEDEF WINPE_EXPORT +INLINE void* STDCALL winpe_findmoduleaex( + PPEB peb, char *modulename); +#define winpe_findmodulea(modulename) winpe_findmoduleaex(NULL, modulename) + +/* + return LoadLibraryA func addr +*/ +WINPEDEF WINPE_EXPORT +INLINE PROC winpe_findloadlibrarya(); + +/* + return GetProcAddress func addr +*/ +WINPEDEF WINPE_EXPORT +INLINE PROC winpe_findgetprocaddress(); + +/* + find a valid space address start from imagebase with imagesize + use PFN_VirtualQuery for better use + return va with imagesize +*/ +WINPEDEF WINPE_EXPORT +INLINE void* STDCALL winpe_findspace( + size_t imagebase, size_t imagesize, size_t alignsize, + PFN_VirtualQuery pfnVirtualQuery); + +// PE load, adjust functions +/* + for overlay section in a pe file + return the overlay offset +*/ +WINPEDEF WINPE_EXPORT +INLINE size_t STDCALL winpe_overlayoffset(const void *rawpe); + +/* + load the origin rawpe in memory buffer by mem align + return memsize +*/ +WINPEDEF WINPE_EXPORT +INLINE size_t STDCALL winpe_memload( + const void *rawpe, size_t rawsize, + void *mempe, size_t memsize, + bool_t same_align); + +/* + realoc the addrs for the mempe addr as image base + origin image base usually at 0x00400000, 0x0000000180000000 + new image base mush be divided by 0x10000, if use loadlibrary + return realoc count +*/ +WINPEDEF WINPE_EXPORT +INLINE size_t STDCALL winpe_memreloc( + void *mempe, size_t newimagebase); + +/* + load the iat for the mempe, use rvafunc for winpe_memfindexp + return iat count +*/ +WINPEDEF WINPE_EXPORT +INLINE size_t STDCALL winpe_membindiat(void *mempe, + PFN_LoadLibraryA pfnLoadLibraryA, + PFN_GetProcAddress pfnGetProcAddress); + +/* + exec the tls callbacks for the mempe, before dll oep load + reason is for function PIMAGE_TLS_CALLBACK + return tls count +*/ +WINPEDEF WINPE_EXPORT +INLINE size_t STDCALL winpe_membindtls(void *mempe, DWORD reason); + +/* + find the iat addres, for call [iat] + return target iat va +*/ +WINPEDEF WINPE_EXPORT +INLINE void* STDCALL winpe_memfindiat(void *mempe, + LPCSTR dllname, LPCSTR funcname); + +/* + find the exp addres, the same as GetProcAddress + without forward to other dll + such as NTDLL.RtlInitializeSListHead + return target exp va +*/ +WINPEDEF WINPE_EXPORT +INLINE void* STDCALL winpe_memfindexp( + void *mempe, LPCSTR funcname); + + +WINPEDEF WINPE_EXPORT +INLINE void* STDCALL winpe_memfindexpcrc32( + void* mempe, uint32_t crc32); + +/* + forward the exp to the final expva + return the final exp va +*/ +WINPEDEF WINPE_EXPORT +INLINE void* STDCALL winpe_memforwardexp( + void *mempe, size_t exprva, + PFN_LoadLibraryA pfnLoadLibraryA, + PFN_GetProcAddress pfnGetProcAddress); + +// PE modify function +/* + change the oep of the pe if newoeprva!=0 + return the old oep rva +*/ +WINPEDEF WINPE_EXPORT +INLINE DWORD STDCALL winpe_oepval( + void *mempe, DWORD newoeprva); + +/* + change the imagebase of the pe if newimagebase!=0 + return the old imagebase va +*/ +WINPEDEF WINPE_EXPORT +INLINE size_t STDCALL winpe_imagebaseval( + void *mempe, size_t newimagebase); + +/* + change the imagesize of the pe if newimagesize!=0 + return the old imagesize +*/ +WINPEDEF WINPE_EXPORT +INLINE size_t STDCALL winpe_imagesizeval( + void *pe, size_t newimagesize); + +/* + close the aslr feature of an pe +*/ +WINPEDEF WINPE_EXPORT +INLINE void STDCALL winpe_noaslr(void *pe); + +/* + Append a section header in a pe, sect rva will be ignored + the mempe size must be enough for extend a section + return image size +*/ +WINPEDEF WINPE_EXPORT +INLINE size_t STDCALL winpe_appendsecth( + void *mempe, PIMAGE_SECTION_HEADER psecth); + + +#ifdef __cplusplus +} +#endif + + +#ifdef WINPE_IMPLEMENTATION + +#ifndef _DEBUG +#ifndef NDEBUG +#define NDEBUG +#endif +#endif + +#if defined(__TINYC__) +#ifdef _WIN64 +#pragma pack(8) +#else +#pragma pack(4) +#endif +#endif + +#include +#include +#include +#include + +// util INLINE functions +INLINE size_t _winpeinl_strlen(const char* str1) +{ + const char* p = str1; + while(*p) p++; + return p - str1; +} + +INLINE int _winpeinl_stricmp(const char *str1, const char *str2) +{ + int i=0; + while(str1[i]!=0 && str2[i]!=0) + { + if (str1[i] == str2[i] + || str1[i] + 0x20 == str2[i] + || str2[i] + 0x20 == str1[i]) + { + i++; + } + else + { + return (int)str1[i] - (int)str2[i]; + } + } + return (int)str1[i] - (int)str2[i]; +} + +INLINE int _winpeinl_stricmp2(const char *str1, const wchar_t* str2) +{ + int i=0; + while(str1[i]!=0 && str2[i]!=0) + { + if ((wchar_t)str1[i] == str2[i] + || (wchar_t)str1[i] + 0x20 == str2[i] + || str2[i] + 0x20 == (wchar_t)str1[i]) + { + i++; + } + else + { + return (int)str1[i] - (int)str2[i]; + } + } + return (int)str1[i] - (int)str2[i]; +} + +INLINE uint32_t _winpeinl_crc32(const void *buf, size_t n) +{ + uint32_t crc32 = ~0; + for(size_t i=0; i< n; i++) + { + crc32 ^= *(const uint8_t*)((uint8_t*)buf+i); + + for(int i = 0; i < 8; i++) + { + uint32_t t = ~((crc32&1) - 1); + crc32 = (crc32>>1) ^ (0xEDB88320 & t); + } + } + return ~crc32; +} + +INLINE void* _winpeinl_memset(void *buf, int ch, size_t n) +{ + char *p = buf; + for(size_t i=0;i0) + { + overlay = malloc(*poverlaysize); + memcpy(overlay, (uint8_t*)rawpe+overlayoffset, *poverlaysize); + } + } + free(rawpe); + return overlay; +} + +WINPEDEF WINPE_EXPORT +INLINE void* STDCALL winpe_memLoadLibrary(void *mempe) +{ + PFN_LoadLibraryA pfnLoadLibraryA = + (PFN_LoadLibraryA)winpe_findloadlibrarya(); + PFN_GetProcAddress pfnGetProcAddress = + (PFN_GetProcAddress)winpe_findgetprocaddress(); + return winpe_memLoadLibraryEx(mempe, 0, + WINPE_LDFLAG_MEMFIND | WINPE_LDFLAG_MEMALLOC, + pfnLoadLibraryA, pfnGetProcAddress); +} + +WINPEDEF WINPE_EXPORT +INLINE void* STDCALL winpe_memLoadLibraryEx(void *mempe, + size_t imagebase, DWORD flag, + PFN_LoadLibraryA pfnLoadLibraryA, + PFN_GetProcAddress pfnGetProcAddress) +{ + // bind windows api + char name_kernel32[] = { 'k', 'e', 'r', 'n', 'e', 'l', '3', '2', '.', 'd', 'l', 'l' , '\0'}; + char name_VirtualQuery[] = {'V', 'i', 'r', 't', 'u', 'a', 'l', 'Q', 'u', 'e', 'r', 'y', '\0'}; + char name_VirtualAlloc[] = {'V', 'i', 'r', 't', 'u', 'a', 'l', 'A', 'l', 'l', 'o', 'c', '\0'}; + char name_VirtualProtect[] = {'V', 'i', 'r', 't', 'u', 'a', 'l', 'P', 'r', 'o', 't', 'e', 'c', 't', '\0'}; + HMODULE hmod_kernel32 = pfnLoadLibraryA(name_kernel32); + PFN_VirtualQuery pfnVirtualQuery = (PFN_VirtualQuery) + pfnGetProcAddress(hmod_kernel32, name_VirtualQuery); + PFN_VirtualAlloc pfnVirtualAlloc = (PFN_VirtualAlloc) + pfnGetProcAddress(hmod_kernel32, name_VirtualAlloc); + PFN_VirtualProtect pfnVirtualProtect =(PFN_VirtualProtect) + pfnGetProcAddress(hmod_kernel32, name_VirtualProtect); + assert(pfnVirtualQuery!=0 && pfnVirtualAlloc!=0 && pfnVirtualProtect!=0); + + // find proper imagebase + size_t imagesize = winpe_imagesizeval(mempe, 0); + if(flag & WINPE_LDFLAG_MEMFIND) + { + imagebase = winpe_imagebaseval(mempe, 0); + imagebase = (size_t)winpe_findspace(imagebase, + imagesize, 0x10000, pfnVirtualQuery); + } + if(flag & WINPE_LDFLAG_MEMALLOC) // find proper memory to reloc + { + + imagebase = (size_t)pfnVirtualAlloc((void*)imagebase, + imagesize, MEM_COMMIT | MEM_RESERVE, + PAGE_EXECUTE_READWRITE); + if(!imagebase) // try alloc in arbitary place + { + imagebase = (size_t)pfnVirtualAlloc(NULL, + imagesize, MEM_COMMIT, + PAGE_EXECUTE_READWRITE); + if(!imagebase) return NULL; + } + else + { + imagebase = (size_t)pfnVirtualAlloc((void*)imagebase, + imagesize, MEM_COMMIT, PAGE_EXECUTE_READWRITE); + if(!imagebase) return NULL; + } + } + + // copy to imagebase + if(!imagebase) + { + imagebase = (size_t)mempe; + } + else + { + DWORD oldprotect; + pfnVirtualProtect((void*)imagebase, imagesize, + PAGE_EXECUTE_READWRITE, &oldprotect); + _winpeinl_memcpy((void*)imagebase, mempe, imagesize); + pfnVirtualProtect((void*)imagebase, imagesize, + oldprotect, &oldprotect); + } + + // initial memory module + if(!winpe_memreloc((void*)imagebase, imagebase)) + return NULL; + if(!winpe_membindiat((void*)imagebase, + pfnLoadLibraryA, pfnGetProcAddress)) return NULL; + winpe_membindtls(mempe, DLL_PROCESS_ATTACH); + PFN_DllMain pfnDllMain = (PFN_DllMain) + (imagebase + winpe_oepval((void*)imagebase, 0)); + pfnDllMain((HINSTANCE)imagebase, DLL_PROCESS_ATTACH, NULL); + return (void*)imagebase; +} + +WINPEDEF WINPE_EXPORT +INLINE BOOL STDCALL winpe_memFreeLibrary(void *mempe) +{ + PFN_LoadLibraryA pfnLoadLibraryA = + (PFN_LoadLibraryA)winpe_findloadlibrarya(); + PFN_GetProcAddress pfnGetProcAddress = + (PFN_GetProcAddress)winpe_findgetprocaddress(); + return winpe_memFreeLibraryEx(mempe, + pfnLoadLibraryA, pfnGetProcAddress); +} + +WINPEDEF WINPE_EXPORT +INLINE BOOL STDCALL winpe_memFreeLibraryEx(void *mempe, + PFN_LoadLibraryA pfnLoadLibraryA, + PFN_GetProcAddress pfnGetProcAddress) +{ + char name_kernel32[] = {'k', 'e', 'r', 'n', 'e', 'l', '3', '2', '\0'}; + char name_VirtualFree[] = {'V', 'i', 'r', 't', 'u', 'a', 'l', 'F', 'r', 'e', 'e', '\0'}; + HMODULE hmod_kernel32 = pfnLoadLibraryA(name_kernel32); + PFN_VirtualFree pfnVirtualFree = (PFN_VirtualFree) + pfnGetProcAddress(hmod_kernel32, name_VirtualFree); + PFN_DllMain pfnDllMain = (PFN_DllMain) + ((uint8_t*)mempe + winpe_oepval(mempe, 0)); + winpe_membindtls(mempe, DLL_PROCESS_DETACH); + pfnDllMain((HINSTANCE)mempe, DLL_PROCESS_DETACH, NULL); + return pfnVirtualFree(mempe, 0, MEM_FREE); +} + +WINPEDEF WINPE_EXPORT +INLINE PROC STDCALL winpe_memGetProcAddress( + void *mempe, const char *funcname) +{ + void* expva = winpe_memfindexp(mempe, funcname); + size_t exprva = (size_t)((uint8_t*)expva - (uint8_t*)mempe); + return (PROC)winpe_memforwardexp(mempe, exprva, // to avoid infinity loop + (PFN_LoadLibraryA)winpe_findloadlibrarya(), + (PFN_GetProcAddress)winpe_findgetprocaddress()); +} + +// PE query functions +WINPEDEF WINPE_EXPORT +INLINE void* winpe_findkernel32() +{ + // return (void*)LoadLibrary("kernel32.dll"); + // TEB->PEB->Ldr->InMemoryOrderLoadList->curProgram->ntdll->kernel32 + void *kerenl32 = NULL; + +#ifndef WINPE_NOASM +#ifdef _WIN64 + __asm{ + mov rax, gs:[60h]; peb + mov rax, [rax+18h]; ldr + mov rax, [rax+20h]; InMemoryOrderLoadList, currentProgramEntry + mov rax, [rax]; ntdllEntry, currentProgramEntry->->Flink + mov rax, [rax]; kernel32Entry, ntdllEntry->Flink + mov rax, [rax-10h+30h]; kernel32.DllBase + mov kerenl32, rax; + } +#else + __asm{ + mov eax, fs:[30h]; peb + mov eax, [eax+0ch]; ldr + mov eax, [eax+14h]; InMemoryOrderLoadList, currentProgramEntry + mov eax, [eax]; ntdllEntry, currentProgramEntry->->Flink + mov eax, [eax]; kernel32Entry, ntdllEntry->Flink + mov eax, [eax - 8h +18h]; kernel32.DllBase + mov kerenl32, eax; + } +#endif +#else + char name_kernel32[] = { 'k', 'e', 'r', 'n', 'e', 'l', '3', '2', '.', 'd', 'l', 'l' , '\0' }; + kerenl32 = winpe_findmodulea(name_kernel32); +#endif + + return kerenl32; +} + +WINPEDEF WINPE_EXPORT +INLINE void* STDCALL winpe_findmoduleaex( + PPEB peb, char *modulename) +{ + typedef struct _LDR_ENTRY // has 3 kinds of pointer link list + { + LIST_ENTRY InLoadOrderLinks; // this has link pointer + LIST_ENTRY InMemoryOrderLinks; // order is program, ntdll, kernel32.dll + LIST_ENTRY InInitializationOrderLinks;//to next entry in same place + PVOID DllBase; // 0x18, 0x30 + PVOID EntryPoint; + ULONG SizeOfImage; + UNICODE_STRING FullDllName; + UNICODE_STRING BaseDllName; + ULONG Flags; + USHORT LoadCount; + USHORT TlsIndex; + union + { + LIST_ENTRY HashLinks; + struct + { + PVOID SectionPointer; + ULONG CheckSum; + }; + }; + ULONG TimeDateStamp; + } LDR_ENTRY, *PLDR_ENTRY; // use this because of mingw bug + + PLDR_ENTRY ldrentry = NULL; + PPEB_LDR_DATA ldr = NULL; + + + if(!peb) + { + PTEB teb = NtCurrentTeb(); +#ifdef _WIN64 + peb = *(PPEB*)((uint8_t*)teb + 0x60); +#else + peb = *(PPEB*)((uint8_t*)teb + 0x30); +#endif + } + +#ifdef _WIN64 + ldr = *(PPEB_LDR_DATA*)((uint8_t*)peb + 0x18); +#else + ldr = *(PPEB_LDR_DATA*)((uint8_t*)peb + 0xC); +#endif + + // InMemoryOrderModuleList is the second entry + ldrentry = (PLDR_ENTRY)((size_t) + ldr->InMemoryOrderModuleList.Flink - 2*sizeof(size_t)); + if(!modulename) + { + return ldrentry->DllBase; + } + while(ldrentry->InMemoryOrderLinks.Flink != + ldr->InMemoryOrderModuleList.Flink) + { + PUNICODE_STRING ustr = &ldrentry->FullDllName; + int i; + for(i=ustr->Length/2-1; i>0 && ustr->Buffer[i]!='\\';i--); + if(ustr->Buffer[i]=='\\') i++; + if(_winpeinl_stricmp2(modulename, ustr->Buffer + i)==0) + { + return ldrentry->DllBase; + } + ldrentry = (PLDR_ENTRY)((size_t) + ldrentry->InMemoryOrderLinks.Flink - 2*sizeof(size_t)); + } + return NULL; +} + +WINPEDEF WINPE_EXPORT +INLINE PROC winpe_findloadlibrarya() +{ + // return (PROC)LoadLibraryA; + HMODULE hmod_kernel32 = (HMODULE)winpe_findkernel32(); + char name_LoadLibraryA[] = {'L', 'o', 'a', 'd', 'L', 'i', 'b', 'r', 'a', 'r', 'y', 'A', '\0'}; + return (PROC)winpe_memfindexp( // suppose exp no forward, to avoid recursive + (void*)hmod_kernel32, name_LoadLibraryA); +} + +WINPEDEF WINPE_EXPORT +INLINE PROC winpe_findgetprocaddress() +{ + // return (PROC)GetProcAddress; + HMODULE hmod_kernel32 = (HMODULE)winpe_findkernel32(); + char name_GetProcAddress[] = {'G', 'e', 't', 'P', 'r', 'o', 'c', 'A', 'd', 'd', 'r', 'e', 's', 's', '\0'}; + return (PROC)winpe_memfindexp(hmod_kernel32, name_GetProcAddress); +} + +WINPEDEF WINPE_EXPORT +INLINE void* STDCALL winpe_findspace( + size_t imagebase, size_t imagesize, size_t alignsize, + PFN_VirtualQuery pfnVirtualQuery) +{ +#define MAX_QUERY 0x1000 + size_t addr = imagebase; + MEMORY_BASIC_INFORMATION minfo; + for (int i=0;i= imagesize) + return (void*)addr; + addr += minfo.RegionSize; + } + return NULL; +} + +// PE load, adjust functions +WINPEDEF WINPE_EXPORT +INLINE size_t STDCALL winpe_overlayoffset(const void *rawpe) +{ + PIMAGE_DOS_HEADER pDosHeader = (PIMAGE_DOS_HEADER)rawpe; + PIMAGE_NT_HEADERS pNtHeader = (PIMAGE_NT_HEADERS) + ((uint8_t*)rawpe + pDosHeader->e_lfanew); + PIMAGE_FILE_HEADER pFileHeader = &pNtHeader->FileHeader; + PIMAGE_OPTIONAL_HEADER pOptHeader = &pNtHeader->OptionalHeader; + PIMAGE_DATA_DIRECTORY pDataDirectory = pOptHeader->DataDirectory; + PIMAGE_SECTION_HEADER pSectHeader = (PIMAGE_SECTION_HEADER) + ((uint8_t*)pOptHeader + pFileHeader->SizeOfOptionalHeader); + WORD sectNum = pFileHeader->NumberOfSections; + + return pSectHeader[sectNum-1].PointerToRawData + + pSectHeader[sectNum-1].SizeOfRawData; +} + +WINPEDEF WINPE_EXPORT +INLINE size_t STDCALL winpe_memload( + const void *rawpe, size_t rawsize, + void *mempe, size_t memsize, + bool_t same_align) +{ + // load rawpe to memalign + PIMAGE_DOS_HEADER pDosHeader = (PIMAGE_DOS_HEADER)rawpe; + PIMAGE_NT_HEADERS pNtHeader = (PIMAGE_NT_HEADERS) + ((uint8_t*)rawpe + pDosHeader->e_lfanew); + PIMAGE_FILE_HEADER pFileHeader = &pNtHeader->FileHeader; + PIMAGE_OPTIONAL_HEADER pOptHeader = &pNtHeader->OptionalHeader; + PIMAGE_SECTION_HEADER pSectHeader = (PIMAGE_SECTION_HEADER) + ((uint8_t*)pOptHeader + pFileHeader->SizeOfOptionalHeader); + WORD sectNum = pFileHeader->NumberOfSections; + size_t imagesize = pOptHeader->SizeOfImage; + if(!mempe) return imagesize; + else if(memsize!=0 && memsizeSizeOfHeaders); + + for(WORD i=0;ie_lfanew); + pFileHeader = &pNtHeader->FileHeader; + pOptHeader = &pNtHeader->OptionalHeader; + pSectHeader = (PIMAGE_SECTION_HEADER) + ((uint8_t*)pOptHeader + pFileHeader->SizeOfOptionalHeader); + sectNum = pFileHeader->NumberOfSections; + + pOptHeader->FileAlignment = pOptHeader->SectionAlignment; + + for(WORD i=0;ie_lfanew); + PIMAGE_FILE_HEADER pFileHeader = &pNtHeader->FileHeader; + PIMAGE_OPTIONAL_HEADER pOptHeader = &pNtHeader->OptionalHeader; + PIMAGE_DATA_DIRECTORY pDataDirectory = pOptHeader->DataDirectory; + PIMAGE_DATA_DIRECTORY pRelocEntry = &pDataDirectory[IMAGE_DIRECTORY_ENTRY_BASERELOC]; + + DWORD reloc_count = 0; + DWORD reloc_offset = 0; + int64_t shift = (int64_t)newimagebase - + (int64_t)pOptHeader->ImageBase; + while (reloc_offset < pRelocEntry->Size) + { + PIMAGE_BASE_RELOCATION pBaseReloc = (PIMAGE_BASE_RELOCATION) + ((uint8_t*)mempe + pRelocEntry->VirtualAddress + reloc_offset); + PRELOCOFFSET pRelocOffset = (PRELOCOFFSET)((uint8_t*)pBaseReloc + + sizeof(IMAGE_BASE_RELOCATION)); + DWORD item_num = (pBaseReloc->SizeOfBlock - // RELOCOFFSET block num + sizeof(IMAGE_BASE_RELOCATION)) / sizeof(RELOCOFFSET); + for (size_t i = 0; i < item_num; i++) + { + if (!pRelocOffset[i].type && + !pRelocOffset[i].offset) continue; + DWORD targetoffset = pBaseReloc->VirtualAddress + + pRelocOffset[i].offset; + size_t *paddr = (size_t *)((uint8_t*)mempe + targetoffset); + size_t relocaddr = (size_t)((int64_t)*paddr + shift); + //printf("reloc 0x%08x->0x%08x\n", *paddr, relocaddr); + *paddr = relocaddr; + } + reloc_offset += sizeof(IMAGE_BASE_RELOCATION) + + sizeof(RELOCOFFSET) * item_num; + reloc_count += item_num; + } + pOptHeader->ImageBase = newimagebase; + return reloc_count; +} + +WINPEDEF WINPE_EXPORT +INLINE size_t STDCALL winpe_membindiat(void *mempe, + PFN_LoadLibraryA pfnLoadLibraryA, + PFN_GetProcAddress pfnGetProcAddress) +{ + PIMAGE_DOS_HEADER pDosHeader = (PIMAGE_DOS_HEADER)mempe; + PIMAGE_NT_HEADERS pNtHeader = (PIMAGE_NT_HEADERS) + ((uint8_t*)mempe + pDosHeader->e_lfanew); + PIMAGE_FILE_HEADER pFileHeader = &pNtHeader->FileHeader; + PIMAGE_OPTIONAL_HEADER pOptHeader = &pNtHeader->OptionalHeader; + PIMAGE_DATA_DIRECTORY pDataDirectory = pOptHeader->DataDirectory; + PIMAGE_DATA_DIRECTORY pImpEntry = + &pDataDirectory[IMAGE_DIRECTORY_ENTRY_IMPORT]; + PIMAGE_IMPORT_DESCRIPTOR pImpDescriptor = + (PIMAGE_IMPORT_DESCRIPTOR)((uint8_t*)mempe + pImpEntry->VirtualAddress); + + PIMAGE_THUNK_DATA pFtThunk = NULL; + PIMAGE_THUNK_DATA pOftThunk = NULL; + LPCSTR pDllName = NULL; + PIMAGE_IMPORT_BY_NAME pImpByName = NULL; + size_t funcva = 0; + char *funcname = NULL; + + // origin GetProcAddress will crash at InitializeSListHead + if(!pfnLoadLibraryA) pfnLoadLibraryA = + (PFN_LoadLibraryA)winpe_findloadlibrarya(); + if(!pfnGetProcAddress) pfnGetProcAddress = + (PFN_GetProcAddress)winpe_findgetprocaddress(); + + DWORD iat_count = 0; + for (; pImpDescriptor->Name; pImpDescriptor++) + { + pDllName = (LPCSTR)((uint8_t*)mempe + pImpDescriptor->Name); + pFtThunk = (PIMAGE_THUNK_DATA) + ((uint8_t*)mempe + pImpDescriptor->FirstThunk); + pOftThunk = (PIMAGE_THUNK_DATA) + ((uint8_t*)mempe + pImpDescriptor->OriginalFirstThunk); + size_t dllbase = (size_t)pfnLoadLibraryA(pDllName); + if(!dllbase) return 0; + + for (int j=0; pFtThunk[j].u1.Function + && pOftThunk[j].u1.Function; j++) + { + size_t _addr = (size_t)((uint8_t*)mempe + pOftThunk[j].u1.AddressOfData); + if(sizeof(size_t)>4) // x64 + { + if(((uint64_t)_addr>>63) == 1) + { + funcname = (char *)(_addr & 0x000000000000ffff); + } + else + { + pImpByName=(PIMAGE_IMPORT_BY_NAME)_addr; + funcname = pImpByName->Name; + } + } + else + { + if(((size_t)pImpByName>>31) == 1) + { + funcname = (char *)(_addr & 0x0000ffff); + } + else + { + pImpByName=(PIMAGE_IMPORT_BY_NAME)_addr; + funcname = pImpByName->Name; + } + } + + funcva = (size_t)pfnGetProcAddress( + (HMODULE)dllbase, funcname); + if(!funcva) continue; + pFtThunk[j].u1.Function = funcva; + assert(funcva == (size_t)GetProcAddress( + (HMODULE)dllbase, funcname)); + iat_count++; + } + } + return iat_count; +} + +WINPEDEF WINPE_EXPORT +INLINE size_t STDCALL winpe_membindtls(void *mempe, DWORD reason) +{ + PIMAGE_DOS_HEADER pDosHeader = (PIMAGE_DOS_HEADER)mempe; + PIMAGE_NT_HEADERS pNtHeader = (PIMAGE_NT_HEADERS) + ((uint8_t*)mempe + pDosHeader->e_lfanew); + PIMAGE_FILE_HEADER pFileHeader = &pNtHeader->FileHeader; + PIMAGE_OPTIONAL_HEADER pOptHeader = &pNtHeader->OptionalHeader; + PIMAGE_DATA_DIRECTORY pDataDirectory = pOptHeader->DataDirectory; + PIMAGE_DATA_DIRECTORY pTlsDirectory = + &pDataDirectory[IMAGE_DIRECTORY_ENTRY_TLS]; + if(!pTlsDirectory->VirtualAddress) return 0; + + size_t tls_count = 0; + PIMAGE_TLS_DIRECTORY pTlsEntry = (PIMAGE_TLS_DIRECTORY) + ((uint8_t*)mempe + pTlsDirectory->VirtualAddress); + PIMAGE_TLS_CALLBACK *tlscb= (PIMAGE_TLS_CALLBACK*) + pTlsEntry->AddressOfCallBacks; + if(tlscb) + { + while(*tlscb) + { + (*tlscb)(mempe, reason, NULL); + tlscb++; + tls_count++; + } + } + return tls_count; +} + +WINPEDEF WINPE_EXPORT +INLINE void* STDCALL winpe_memfindiat(void *mempe, + LPCSTR dllname, LPCSTR funcname) +{ + PIMAGE_DOS_HEADER pDosHeader = (PIMAGE_DOS_HEADER)mempe; + PIMAGE_NT_HEADERS pNtHeader = (PIMAGE_NT_HEADERS) + ((uint8_t*)mempe + pDosHeader->e_lfanew); + PIMAGE_FILE_HEADER pFileHeader = &pNtHeader->FileHeader; + PIMAGE_OPTIONAL_HEADER pOptHeader = &pNtHeader->OptionalHeader; + PIMAGE_DATA_DIRECTORY pDataDirectory = pOptHeader->DataDirectory; + PIMAGE_DATA_DIRECTORY pImpEntry = + &pDataDirectory[IMAGE_DIRECTORY_ENTRY_IMPORT]; + PIMAGE_IMPORT_DESCRIPTOR pImpDescriptor = + (PIMAGE_IMPORT_DESCRIPTOR)((uint8_t*)mempe + pImpEntry->VirtualAddress); + + PIMAGE_THUNK_DATA pFtThunk = NULL; + PIMAGE_THUNK_DATA pOftThunk = NULL; + LPCSTR pDllName = NULL; + PIMAGE_IMPORT_BY_NAME pImpByName = NULL; + + for (; pImpDescriptor->Name; pImpDescriptor++) + { + pDllName = (LPCSTR)((uint8_t*)mempe + pImpDescriptor->Name); + if(dllname && _winpeinl_stricmp(pDllName, dllname)!=0) continue; + pFtThunk = (PIMAGE_THUNK_DATA) + ((uint8_t*)mempe + pImpDescriptor->FirstThunk); + pOftThunk = (PIMAGE_THUNK_DATA) + ((uint8_t*)mempe + pImpDescriptor->OriginalFirstThunk); + + for (int j=0; pFtThunk[j].u1.Function + && pOftThunk[j].u1.Function; j++) + { + pImpByName=(PIMAGE_IMPORT_BY_NAME)((uint8_t*)mempe + + pOftThunk[j].u1.AddressOfData); + if((size_t)funcname < MAXWORD) // ordinary + { + WORD funcord = LOWORD(funcname); + if(pImpByName->Hint == funcord) + return &pFtThunk[j]; + } + else + { + if(_winpeinl_stricmp(pImpByName->Name, funcname)==0) + return &pFtThunk[j]; + } + } + } + return 0; +} + +WINPEDEF WINPE_EXPORT +INLINE void* STDCALL winpe_memfindexp( + void *mempe, LPCSTR funcname) +{ + PIMAGE_DOS_HEADER pDosHeader = (PIMAGE_DOS_HEADER)mempe; + PIMAGE_NT_HEADERS pNtHeader = (PIMAGE_NT_HEADERS) + ((uint8_t*)mempe + pDosHeader->e_lfanew); + PIMAGE_FILE_HEADER pFileHeader = &pNtHeader->FileHeader; + PIMAGE_OPTIONAL_HEADER pOptHeader = &pNtHeader->OptionalHeader; + PIMAGE_DATA_DIRECTORY pDataDirectory = pOptHeader->DataDirectory; + PIMAGE_DATA_DIRECTORY pExpEntry = + &pDataDirectory[IMAGE_DIRECTORY_ENTRY_EXPORT]; + PIMAGE_EXPORT_DIRECTORY pExpDescriptor = + (PIMAGE_EXPORT_DIRECTORY)((uint8_t*)mempe + pExpEntry->VirtualAddress); + + WORD *ordrva = (WORD*)((uint8_t*)mempe + + pExpDescriptor->AddressOfNameOrdinals); + DWORD *namerva = (DWORD*)((uint8_t*)mempe + + pExpDescriptor->AddressOfNames); + DWORD *funcrva = (DWORD*)((uint8_t*)mempe + + pExpDescriptor->AddressOfFunctions); + if((size_t)funcname <= MAXWORD) // find by ordnial + { + WORD ordbase = LOWORD(pExpDescriptor->Base) - 1; + WORD funcord = LOWORD(funcname); + return (void*)((uint8_t*)mempe + funcrva[ordrva[funcord-ordbase]]); + } + else + { + for(DWORD i=0;iNumberOfNames;i++) + { + LPCSTR curname = (LPCSTR)((uint8_t*)mempe+namerva[i]); + if(_winpeinl_stricmp(curname, funcname)==0) + { + return (void*)((uint8_t*)mempe + funcrva[ordrva[i]]); + } + } + } + return NULL; +} + +WINPEDEF WINPE_EXPORT +INLINE void* STDCALL winpe_memfindexpcrc32( + void* mempe, uint32_t crc32) +{ + PIMAGE_DOS_HEADER pDosHeader = (PIMAGE_DOS_HEADER)mempe; + PIMAGE_NT_HEADERS pNtHeader = (PIMAGE_NT_HEADERS) + ((uint8_t*)mempe + pDosHeader->e_lfanew); + PIMAGE_FILE_HEADER pFileHeader = &pNtHeader->FileHeader; + PIMAGE_OPTIONAL_HEADER pOptHeader = &pNtHeader->OptionalHeader; + PIMAGE_DATA_DIRECTORY pDataDirectory = pOptHeader->DataDirectory; + PIMAGE_DATA_DIRECTORY pExpEntry = + &pDataDirectory[IMAGE_DIRECTORY_ENTRY_EXPORT]; + PIMAGE_EXPORT_DIRECTORY pExpDescriptor = + (PIMAGE_EXPORT_DIRECTORY)((uint8_t*)mempe + pExpEntry->VirtualAddress); + + WORD* ordrva = (WORD*)((uint8_t*)mempe + + pExpDescriptor->AddressOfNameOrdinals); + DWORD* namerva = (DWORD*)((uint8_t*)mempe + + pExpDescriptor->AddressOfNames); + DWORD* funcrva = (DWORD*)((uint8_t*)mempe + + pExpDescriptor->AddressOfFunctions); + for (DWORD i = 0; i < pExpDescriptor->NumberOfNames; i++) + { + LPCSTR curname = (LPCSTR)((uint8_t*)mempe + namerva[i]); + if (crc32==_winpeinl_crc32(curname, _winpeinl_strlen(curname))) + { + return (void*)((uint8_t*)mempe + funcrva[ordrva[i]]); + } + } + return NULL; +} + +WINPEDEF WINPE_EXPORT +INLINE void* STDCALL winpe_memforwardexp( + void *mempe, size_t exprva, + PFN_LoadLibraryA pfnLoadLibraryA, + PFN_GetProcAddress pfnGetProcAddress) +{ + // this function might have infinite loop + // such as this situation + // kerenl32.dll, GetProcessMitigationPolicy -> api-ms-win-core-processthreads-l1-1-1.dll -> kerenl32.dll, GetProcessMitigationPolicys + size_t dllbase = (size_t)mempe; + while (1) + { + PIMAGE_DOS_HEADER pDosHeader = (PIMAGE_DOS_HEADER)dllbase; + PIMAGE_NT_HEADERS pNtHeader = (PIMAGE_NT_HEADERS) + ((uint8_t*)dllbase + pDosHeader->e_lfanew); + PIMAGE_OPTIONAL_HEADER pOptHeader = &pNtHeader->OptionalHeader; + PIMAGE_DATA_DIRECTORY pDataDirectory = pOptHeader->DataDirectory; + PIMAGE_DATA_DIRECTORY pExpEntry = + &pDataDirectory[IMAGE_DIRECTORY_ENTRY_EXPORT]; + if(exprva>=pExpEntry->VirtualAddress && + exprva<= pExpEntry->VirtualAddress + pExpEntry->Size) + { + char namebuf[MAX_PATH]; + char *dllname = (char *)(dllbase + exprva); + char *funcname = dllname; + int i=0, j=0; + while(dllname[i]!=0) + { + if(dllname[i]=='.') + { + namebuf[j] = dllname[i]; + namebuf[++j] = 'd'; + namebuf[++j] = 'l'; + namebuf[++j] = 'l'; + namebuf[++j] = '\0'; + funcname = namebuf + j + 1; + } + else + { + namebuf[j]=dllname[i]; + } + i++; + j++; + } + namebuf[j] = '\0'; + dllname = namebuf; + dllbase = (size_t)pfnLoadLibraryA(dllname); + exprva = (size_t)pfnGetProcAddress((HMODULE)dllbase, funcname); + exprva -= dllbase; + } + else + { + return (void*)(dllbase + exprva); + } + } + return NULL; +} + +// PE setting function +WINPEDEF WINPE_EXPORT +INLINE void STDCALL winpe_noaslr(void *pe) +{ + PIMAGE_DOS_HEADER pDosHeader = (PIMAGE_DOS_HEADER)pe; + PIMAGE_NT_HEADERS pNtHeader = (PIMAGE_NT_HEADERS) + ((uint8_t*)pe + pDosHeader->e_lfanew); + PIMAGE_FILE_HEADER pFileHeader = &pNtHeader->FileHeader; + PIMAGE_OPTIONAL_HEADER pOptHeader = &pNtHeader->OptionalHeader; + #ifndef IMAGE_DLLCHARACTERISTICS_DYNAMIC_BASE + #define IMAGE_DLLCHARACTERISTICS_DYNAMIC_BASE 0x0040 + #endif + pOptHeader->DllCharacteristics &= ~IMAGE_DLLCHARACTERISTICS_DYNAMIC_BASE; +} + +WINPEDEF WINPE_EXPORT +INLINE DWORD STDCALL winpe_oepval(void *pe, DWORD newoeprva) +{ + PIMAGE_DOS_HEADER pDosHeader = (PIMAGE_DOS_HEADER)pe; + PIMAGE_NT_HEADERS pNtHeader = (PIMAGE_NT_HEADERS) + ((uint8_t*)pe + pDosHeader->e_lfanew); + PIMAGE_FILE_HEADER pFileHeader = &pNtHeader->FileHeader; + PIMAGE_OPTIONAL_HEADER pOptHeader = &pNtHeader->OptionalHeader; + DWORD orgoep = pOptHeader->AddressOfEntryPoint; + if(newoeprva) pOptHeader->AddressOfEntryPoint = newoeprva; + return orgoep; +} + +WINPEDEF WINPE_EXPORT +INLINE size_t STDCALL winpe_imagebaseval(void *pe, size_t newimagebase) +{ + PIMAGE_DOS_HEADER pDosHeader = (PIMAGE_DOS_HEADER)pe; + PIMAGE_NT_HEADERS pNtHeader = (PIMAGE_NT_HEADERS) + ((uint8_t*)pe + pDosHeader->e_lfanew); + PIMAGE_FILE_HEADER pFileHeader = &pNtHeader->FileHeader; + PIMAGE_OPTIONAL_HEADER pOptHeader = &pNtHeader->OptionalHeader; + size_t imagebase = pOptHeader->ImageBase; + if(newimagebase) pOptHeader->ImageBase = newimagebase; + return imagebase; +} + +WINPEDEF WINPE_EXPORT +INLINE size_t STDCALL winpe_imagesizeval(void *pe, size_t newimagesize) +{ + PIMAGE_DOS_HEADER pDosHeader = (PIMAGE_DOS_HEADER)pe; + PIMAGE_NT_HEADERS pNtHeader = (PIMAGE_NT_HEADERS) + ((uint8_t*)pe + pDosHeader->e_lfanew); + PIMAGE_FILE_HEADER pFileHeader = &pNtHeader->FileHeader; + PIMAGE_OPTIONAL_HEADER pOptHeader = &pNtHeader->OptionalHeader; + size_t imagesize = pOptHeader->SizeOfImage; + if(newimagesize) pOptHeader->SizeOfImage = (DWORD)newimagesize; + return imagesize; +} + +WINPEDEF WINPE_EXPORT +INLINE size_t STDCALL winpe_appendsecth(void *pe, + PIMAGE_SECTION_HEADER psecth) +{ + PIMAGE_DOS_HEADER pDosHeader = (PIMAGE_DOS_HEADER)pe; + PIMAGE_NT_HEADERS pNtHeader = (PIMAGE_NT_HEADERS) + ((uint8_t*)pe + pDosHeader->e_lfanew); + PIMAGE_FILE_HEADER pFileHeader = &pNtHeader->FileHeader; + PIMAGE_OPTIONAL_HEADER pOptHeader = &pNtHeader->OptionalHeader; + PIMAGE_SECTION_HEADER pSectHeader = (PIMAGE_SECTION_HEADER) + ((uint8_t*)pOptHeader + pFileHeader->SizeOfOptionalHeader); + WORD sectNum = pFileHeader->NumberOfSections; + PIMAGE_SECTION_HEADER pLastSectHeader = &pSectHeader[sectNum-1]; + DWORD addr, align; + + // check the space to append section + if(pFileHeader->SizeOfOptionalHeader + + sizeof(IMAGE_SECTION_HEADER) + > pSectHeader[0].PointerToRawData) return 0; + + // fill rva addr + align = pOptHeader->SectionAlignment; + addr = pLastSectHeader->VirtualAddress + pLastSectHeader->Misc.VirtualSize; + if(addr % align) addr += align - addr%align; + psecth->VirtualAddress = addr; + + // fill file offset + align = pOptHeader->FileAlignment; + addr = pLastSectHeader->PointerToRawData+ pLastSectHeader->SizeOfRawData; + if(addr % align) addr += align - addr%align; + psecth->PointerToRawData = addr; + + // adjust the section and imagesize + pFileHeader->NumberOfSections++; + _winpeinl_memcpy(&pSectHeader[sectNum], psecth, sizeof(IMAGE_SECTION_HEADER)); + align = pOptHeader->SectionAlignment; + addr = psecth->VirtualAddress + psecth->Misc.VirtualSize; + if(addr % align) addr += align - addr%align; + pOptHeader->SizeOfImage = addr; + return pOptHeader->SizeOfImage; +} + +#endif +#endif + +/* +history: +v0.1, initial version, with load pe in memory align +V0.1.2, adjust declear name, load pe iat +v0.2, add append section, findiat function +v0.2.2, add function winpe_memfindexp +v0.2.5, INLINE basic functions, better for shellcode +v0.3, add winpe_memloadlibrary, winpe_memGetprocaddress, winpe_memFreelibrary +v0.3.1, fix the stdcall function name by .def, load memory moudule aligned with 0x1000(x86), 0x10000(x64) +v0.3.2, x64 memory load support, winpe_findkernel32, winpe_finmodule by asm +v0.3.3, add ordinal support in winpe_membindiat, add win_membindtls, change all call to STDCALL +v0.3.4, add WINPE_NOASM to make compatible for vs x64 +v0.3.5, add winpe_memfindexpcrc32 */ \ No newline at end of file diff --git a/script/win_console.js b/src/js/winconsole.js similarity index 93% rename from script/win_console.js rename to src/js/winconsole.js index 2eb53d5..8bdf9cb 100644 --- a/script/win_console.js +++ b/src/js/winconsole.js @@ -3,6 +3,8 @@ use this script to allocate a console on some program v0.1, developed by devseed */ +const WINCONSOLE_VERSION = 100; + function hook_console() { const api = new ApiResolver("module"); diff --git a/script/win_file.js b/src/js/winfile.js similarity index 96% rename from script/win_file.js rename to src/js/winfile.js index a941f98..675ac66 100644 --- a/script/win_file.js +++ b/src/js/winfile.js @@ -3,6 +3,8 @@ use this script to log the windows file api function v0.1, developed by devseed */ +const WINFILE_VERSION = 100; + function hook_cfile(idx=0) { const api = new ApiResolver("module"); diff --git a/script/win_redirect.js b/src/js/winredirect.js similarity index 96% rename from script/win_redirect.js rename to src/js/winredirect.js index 93dfb60..fd8c60b 100644 --- a/script/win_redirect.js +++ b/src/js/winredirect.js @@ -4,6 +4,8 @@ such as chcp codepage, replace font, replace path by pattern v0.1, developed by devseed */ +const WINREDIRECT_VERSION = 100; + function chcp(codepage=-1, mute_log=false) { const api = new ApiResolver("module"); diff --git a/script/minor/cpcvt.py b/src/py/codepage.py similarity index 99% rename from script/minor/cpcvt.py rename to src/py/codepage.py index 0c4e88f..b307734 100644 --- a/script/minor/cpcvt.py +++ b/src/py/codepage.py @@ -7,6 +7,8 @@ import argparse from copy import deepcopy +CODEPAGE_VERSION = 110 + def datacpcvt(data: bytearray, texts: list, fromcp='936', tocp='932', middlecp=None, minsize=4, copydata=False, singlematch=False, diff --git a/script/minor/batch_filecpcvt.bat b/src/py/convert_codepage.bat similarity index 50% rename from script/minor/batch_filecpcvt.bat rename to src/py/convert_codepage.bat index ff886aa..afab76d 100644 --- a/script/minor/batch_filecpcvt.bat +++ b/src/py/convert_codepage.bat @@ -1,7 +1,8 @@ @echo off set OUTDIR=%1\convert +set codepage=%~dp0codepage.py mkdir %OUTDIR% for /f "delims=" %%i in ('dir /b /a:-d %1') do ( echo %%i - python cpcvt.py "%1\%%i" -o "%OUTDIR%\%%i" %2 %3 %4 %5 %6 %7 %8 %9 + python %codepage% "%1\%%i" -o "%OUTDIR%\%%i" %2 %3 %4 %5 %6 %7 %8 %9 ) \ No newline at end of file diff --git a/script/minor/batch_ftextexp.bat b/src/py/extract_ftext.bat similarity index 75% rename from script/minor/batch_ftextexp.bat rename to src/py/extract_ftext.bat index 7c03049..08dd560 100644 --- a/script/minor/batch_ftextexp.bat +++ b/src/py/extract_ftext.bat @@ -1,5 +1,5 @@ @echo off -set bintext=.\..\bintext.py +set bintext=%~dp0..\cross_lib\libbintext.py for /f "delims=" %%i in ('dir /b %1') do ( echo %%i python %bintext% %1\%%i -o %1\%%i.txt %2 %3 %4 %5 %6 %7 %8 %9 diff --git a/script/minor/ftextcvt.py b/src/py/ftext.py similarity index 96% rename from script/minor/ftextcvt.py rename to src/py/ftext.py index b5c6099..09880bc 100644 --- a/script/minor/ftextcvt.py +++ b/src/py/ftext.py @@ -15,6 +15,8 @@ from docx.shared import Pt from typing import Union, List, Dict +FTEXT_VERSION = 200 + # util functions def dump_ftext(ftexts1:List[Dict[str,Union[int,str]]], ftexts2: List[Dict[str, Union[int, str]]], diff --git a/script/bintext.py b/src/py/libbintext.py similarity index 97% rename from script/bintext.py rename to src/py/libbintext.py index 640a838..2375b87 100644 --- a/script/bintext.py +++ b/src/py/libbintext.py @@ -10,7 +10,8 @@ import argparse from io import StringIO, BytesIO from typing import Any, Callable, Tuple, Union, List, Dict -from unittest.mock import patch + +LIBBINTEXT_VERSION = 580 # lib functions def iscjk(c: bytes): diff --git a/script/libfont.py b/src/py/libfont.py similarity index 97% rename from script/libfont.py rename to src/py/libfont.py index 43b8479..37c0547 100644 --- a/script/libfont.py +++ b/src/py/libfont.py @@ -15,6 +15,8 @@ from PIL import ImageFont, ImageDraw, Image from typing import Callable, Tuple, Union, List, Dict +LIBFONT_VERSION = 240 + # util functions def dump_tbl(tbl: List[Tuple[bytes, str]], outpath="out.tbl", encoding='utf-8') -> List[str]: diff --git a/script/libtext.py b/src/py/librawtext.py similarity index 96% rename from script/libtext.py rename to src/py/librawtext.py index e622a2b..2839e03 100644 --- a/script/libtext.py +++ b/src/py/librawtext.py @@ -4,12 +4,13 @@ v0.2.2, developed by devseed """ -from pickle import TRUE import re import codecs from io import StringIO from typing import Callable, Tuple, Union, List, Dict +LIBRAWTEXT_VERSION = 220 + # util functions def dump_ftext(ftexts1:List[Dict[str,Union[int,str]]], ftexts2: List[Dict[str, Union[int, str]]], @@ -220,7 +221,7 @@ def count_ftextfilesglphy(filepaths: List[str])\ ftexts = [] for path in filepaths: - _, ftexts2 = load_ftext(path, TRUE) + _, ftexts2 = load_ftext(path, True) ftexts.extend(ftexts2) return count_ftextglphy(ftexts) diff --git a/script/shellcode.py b/src/py/libshellcode.py similarity index 96% rename from script/shellcode.py rename to src/py/libshellcode.py index e28c772..e9b1f06 100644 --- a/script/shellcode.py +++ b/src/py/libshellcode.py @@ -9,6 +9,8 @@ import codecs from typing import Union, List, Dict +LIBSHELLCODE_VERSION = 100 + class coff_filehdr_t(struct.Struct): def __init__(self, data): super().__init__('<2H3I2H') diff --git a/script/texture.py b/src/py/libtexture.py similarity index 97% rename from script/texture.py rename to src/py/libtexture.py index 18d3979..20a4182 100644 --- a/script/texture.py +++ b/src/py/libtexture.py @@ -10,6 +10,8 @@ from queue import Queue from PIL import Image, ImageOps +LIBTEXTURE = 210 + texture_size = {"RGBA8888":4, "RGB5A1": 2, "RGB332":1, "RGBA2222":1} def swizzle_regular(n, start=0, resmat=None): diff --git a/script/win_injectdll.py b/src/py/windllin.py similarity index 97% rename from script/win_injectdll.py rename to src/py/windllin.py index c08cc7b..98c09ac 100644 --- a/script/win_injectdll.py +++ b/src/py/windllin.py @@ -10,6 +10,8 @@ import lief from keystone import Ks, KS_ARCH_X86, KS_MODE_32, KS_MODE_64 +WINDLLIN_VERSION = 320 + def injectdll_iat(exepath, dllpath, outpath="out.exe"): """ This might be regared as virus by windows defender, @@ -472,11 +474,11 @@ def debug(): def main(): if len(sys.argv) < 3: - print("injectdll exepath dllpath [-m|method iat|codecave(default)|codecave2|mem] [-o outpath]") + print("windllin exepath dllpath [-m|method iat|codecave(default)|codecave2|mem] [-o outpath]") return parser = argparse.ArgumentParser( - description="win_injectdll v0.3.2, developed by devseed") + description="windllin v0.3.2, developed by devseed") parser.add_argument('exepath', type=str) parser.add_argument('dllpath', type=str) parser.add_argument('--method', '-m', default='codecave') diff --git a/tool/binstrcvt_gui/binstrcvt_gui.py b/tool/binstrcvt_gui/binstrcvt_gui.py deleted file mode 100644 index e69de29..0000000 diff --git a/tool/bintext/build_bintext_byenv.bat b/tool/bintext/build_bintext_byenv.bat deleted file mode 100644 index 7b787f8..0000000 --- a/tool/bintext/build_bintext_byenv.bat +++ /dev/null @@ -1,10 +0,0 @@ -::@echo off -if not exist "%~dp0\..\..\env" ( - mkdir "%~dp0\..\..\env" -) -pushd "%~dp0\..\..\env" -python -m venv python_base -cd .\python_base\Scripts -python -m pip install pyinstaller -call %1 -popd \ No newline at end of file diff --git a/tool/bintext/build_bintext_nuitkamulti.bat b/tool/bintext/build_bintext_nuitkamulti.bat deleted file mode 100644 index 240d97b..0000000 --- a/tool/bintext/build_bintext_nuitkamulti.bat +++ /dev/null @@ -1,2 +0,0 @@ -:: build multi files -nuitka --standalone --full-compat --show-progress "%~dp0\..\..\script\bintext.py" --windows-icon-from-ico="%~dp0\..\..\asset\default.ico" --output-dir="%~dp0\bin\multi" --assume-yes-for-downloads \ No newline at end of file diff --git a/tool/bintext/build_bintext_nuitkasingle.bat b/tool/bintext/build_bintext_nuitkasingle.bat deleted file mode 100644 index 596ce03..0000000 --- a/tool/bintext/build_bintext_nuitkasingle.bat +++ /dev/null @@ -1,2 +0,0 @@ -:: build single files -nuitka --standalone --onefile --full-compat --show-progress "%~dp0\..\..\script\bintext.py" --windows-icon-from-ico="%~dp0\..\..\asset\default.ico" --output-dir="%~dp0\bin" -o "%~dp0\bin\cbintext.exe" --assume-yes-for-downloads \ No newline at end of file diff --git a/tool/bintext/build_bintext_pyinstallersingle.bat b/tool/bintext/build_bintext_pyinstallersingle.bat deleted file mode 100644 index 9a915b0..0000000 --- a/tool/bintext/build_bintext_pyinstallersingle.bat +++ /dev/null @@ -1 +0,0 @@ -pyinstaller -F "%~dp0\..\..\script\bintext.py" --name "bintext.exe" --distpath="%~dp0\bin" --workpath="%~dp0\bin\obj" --specpath="%~dp0\bin\obj" --icon="%~dp0\..\..\asset\default.ico" --exclude-module=numpy --exclude-module=PIL --console --clean -y \ No newline at end of file diff --git a/tool/ftextcvt/build_ftextcvt_byenv.bat b/tool/ftextcvt/build_ftextcvt_byenv.bat deleted file mode 100644 index feed138..0000000 --- a/tool/ftextcvt/build_ftextcvt_byenv.bat +++ /dev/null @@ -1,11 +0,0 @@ -::@echo off -if not exist "%~dp0\..\..\env" ( - mkdir "%~dp0\..\..\env" -) -pushd "%~dp0\..\..\env" -python -m venv python_docx -cd .\python_docx\Scripts -python -m pip install pyinstaller -python -m pip install python-docx -call %1 -popd \ No newline at end of file diff --git a/tool/ftextcvt/build_ftextcvt_nuitkamulti.bat b/tool/ftextcvt/build_ftextcvt_nuitkamulti.bat deleted file mode 100644 index 918e502..0000000 --- a/tool/ftextcvt/build_ftextcvt_nuitkamulti.bat +++ /dev/null @@ -1,2 +0,0 @@ -:: build multi files -nuitka --standalone --full-compat --show-progress "%~dp0\..\..\script\minor\ftextcvt.py" --windows-icon-from-ico="%~dp0\..\..\asset\default.ico" --output-dir="%~dp0\bin\multi" --assume-yes-for-downloads \ No newline at end of file diff --git a/tool/ftextcvt/build_ftextcvt_nuitkamulti2.bat b/tool/ftextcvt/build_ftextcvt_nuitkamulti2.bat deleted file mode 100644 index 4d14606..0000000 --- a/tool/ftextcvt/build_ftextcvt_nuitkamulti2.bat +++ /dev/null @@ -1,2 +0,0 @@ -:: build multi files -nuitka --mingw64 --standalone --full-compat --show-progress "%~dp0\..\..\script\minor\ftextcvt.py" --windows-icon-from-ico="%~dp0\..\..\asset\default.ico" --output-dir="%~dp0\bin\multi" --assume-yes-for-downloads \ No newline at end of file diff --git a/tool/ftextcvt/build_ftextcvt_nuitkasingle.bat b/tool/ftextcvt/build_ftextcvt_nuitkasingle.bat deleted file mode 100644 index 64e0958..0000000 --- a/tool/ftextcvt/build_ftextcvt_nuitkasingle.bat +++ /dev/null @@ -1,2 +0,0 @@ -:: build single files -nuitka --standalone --onefile --full-compat --show-progress "%~dp0\..\..\script\minor\ftextcvt.py" --windows-icon-from-ico="%~dp0\..\..\asset\default.ico" --output-dir="%~dp0\bin" -o "%~dp0\bin\cftextcvt.exe" --assume-yes-for-downloads \ No newline at end of file diff --git a/tool/ftextcvt/build_ftextcvt_pyinstallersingle.bat b/tool/ftextcvt/build_ftextcvt_pyinstallersingle.bat deleted file mode 100644 index a7f0c93..0000000 --- a/tool/ftextcvt/build_ftextcvt_pyinstallersingle.bat +++ /dev/null @@ -1 +0,0 @@ -pyinstaller -F "%~dp0\..\..\script\minor\ftextcvt.py" --name "ftextcvt.exe" --distpath="%~dp0\bin" --workpath="%~dp0\bin\obj" --specpath="%~dp0\bin\obj" --icon="%~dp0\..\..\asset\default.ico" --exclude-module=numpy --exclude-module=PIL --console --clean -y \ No newline at end of file diff --git a/tool/libwinhook/build_libwinhook.bat b/tool/libwinhook/build_libwinhook.bat deleted file mode 100644 index 81e80f3..0000000 --- a/tool/libwinhook/build_libwinhook.bat +++ /dev/null @@ -1,2 +0,0 @@ -msbuild %~dp0\libwinhook.sln -t:dllloader:rebuild -p:configuration=release -p:Platform=x86 -msbuild %~dp0\libwinhook.sln -t:dllloader:rebuild -p:configuration=release -p:Platform=x64 \ No newline at end of file diff --git a/tool/libwinhook/dllloader/dllloader.vcxproj b/tool/libwinhook/dllloader/dllloader.vcxproj deleted file mode 100644 index a12d3ab..0000000 --- a/tool/libwinhook/dllloader/dllloader.vcxproj +++ /dev/null @@ -1,177 +0,0 @@ - - - - - Debug - Win32 - - - Release - Win32 - - - Debug - x64 - - - Release - x64 - - - - - - - - - - - - - 16.0 - Win32Proj - {A3D9E589-CD2F-4427-804E-3A5865CA3C17} - dllloader - 7.0 - - - - Application - true - v141_xp - MultiByte - - - Application - false - v141_xp - true - MultiByte - - - Application - true - v141_xp - MultiByte - - - Application - false - v141_xp - true - MultiByte - - - - - - - - - - - - - - - - - - - - - true - $(ProjectName)32d - - - false - $(ProjectName)32 - - - true - $(ProjectName)64d - - - false - $(ProjectName)64 - - - - Level3 - true - _CRT_SECURE_NO_WARNINGS; WIN32;_DEBUG;_CONSOLE;%(PreprocessorDefinitions) - true - ./../../../include - MultiThreaded - - - Console - true - Psapi.lib;%(AdditionalDependencies) - - - - - Level3 - true - false - false - _CRT_SECURE_NO_WARNINGS; WIN32;NDEBUG;_CONSOLE;%(PreprocessorDefinitions) - true - ./../../../include - MultiThreaded - MinSpace - Size - Disabled - false - - - Console - true - true - true - Psapi.lib;%(AdditionalDependencies) - - - - - Level3 - true - _CRT_SECURE_NO_WARNINGS; _DEBUG;_CONSOLE;%(PreprocessorDefinitions) - true - ./../../../include - MultiThreaded - - - Console - true - Psapi.lib;%(AdditionalDependencies) - - - - - Level3 - true - false - false - _CRT_SECURE_NO_WARNINGS; NDEBUG;_CONSOLE;%(PreprocessorDefinitions) - true - ./../../../include - MultiThreaded - MinSpace - Size - Disabled - false - - - Console - true - true - true - Psapi.lib;%(AdditionalDependencies) - - - - - - \ No newline at end of file diff --git a/tool/libwinhook/dllloader/dllloader.vcxproj.filters b/tool/libwinhook/dllloader/dllloader.vcxproj.filters deleted file mode 100644 index fcda421..0000000 --- a/tool/libwinhook/dllloader/dllloader.vcxproj.filters +++ /dev/null @@ -1,32 +0,0 @@ - - - - - {4FC737F1-C7A5-4376-A066-2A32D752A2FF} - cpp;c;cc;cxx;c++;cppm;ixx;def;odl;idl;hpj;bat;asm;asmx - - - {93995380-89BD-4b04-88EB-625FBE52EBFB} - h;hh;hpp;hxx;h++;hm;inl;inc;ipp;xsd - - - {67DA6AB6-F800-4c08-8B7A-83BB121AAD01} - rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav;mfcribbon-ms - - - - - 源文件 - - - - - 头文件 - - - - - 资源文件 - - - \ No newline at end of file diff --git a/tool/libwinhook/dllloader/dllloader.vcxproj.user b/tool/libwinhook/dllloader/dllloader.vcxproj.user deleted file mode 100644 index 0f14913..0000000 --- a/tool/libwinhook/dllloader/dllloader.vcxproj.user +++ /dev/null @@ -1,4 +0,0 @@ - - - - \ No newline at end of file diff --git a/tool/libwinhook/libwinhook.sln b/tool/libwinhook/libwinhook.sln deleted file mode 100644 index 2f49669..0000000 --- a/tool/libwinhook/libwinhook.sln +++ /dev/null @@ -1,71 +0,0 @@ - -Microsoft Visual Studio Solution File, Format Version 12.00 -# Visual Studio Version 16 -VisualStudioVersion = 16.0.31613.86 -MinimumVisualStudioVersion = 10.0.40219.1 -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "libwinhook", "libwinhook\libwinhook.vcxproj", "{E14BE7D3-25ED-44AD-8657-2D65874F3986}" -EndProject -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "dllloader", "dllloader\dllloader.vcxproj", "{A3D9E589-CD2F-4427-804E-3A5865CA3C17}" -EndProject -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "test", "test\test.vcxproj", "{AC905C95-1311-4798-8576-F1A08CCE259F}" -EndProject -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "test_hello", "test_hello\test_hello.vcxproj", "{BC2385D0-C79C-4E42-989E-6B2EE268F2D9}" -EndProject -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "test_hellodll", "test_hellodll\test_hellodll.vcxproj", "{162FD21D-EA17-448A-9892-CAD62D6849DB}" -EndProject -Global - GlobalSection(SolutionConfigurationPlatforms) = preSolution - Debug|x64 = Debug|x64 - Debug|x86 = Debug|x86 - Release|x64 = Release|x64 - Release|x86 = Release|x86 - EndGlobalSection - GlobalSection(ProjectConfigurationPlatforms) = postSolution - {E14BE7D3-25ED-44AD-8657-2D65874F3986}.Debug|x64.ActiveCfg = Debug|x64 - {E14BE7D3-25ED-44AD-8657-2D65874F3986}.Debug|x64.Build.0 = Debug|x64 - {E14BE7D3-25ED-44AD-8657-2D65874F3986}.Debug|x86.ActiveCfg = Debug|Win32 - {E14BE7D3-25ED-44AD-8657-2D65874F3986}.Debug|x86.Build.0 = Debug|Win32 - {E14BE7D3-25ED-44AD-8657-2D65874F3986}.Release|x64.ActiveCfg = Release|x64 - {E14BE7D3-25ED-44AD-8657-2D65874F3986}.Release|x64.Build.0 = Release|x64 - {E14BE7D3-25ED-44AD-8657-2D65874F3986}.Release|x86.ActiveCfg = Release|Win32 - {E14BE7D3-25ED-44AD-8657-2D65874F3986}.Release|x86.Build.0 = Release|Win32 - {A3D9E589-CD2F-4427-804E-3A5865CA3C17}.Debug|x64.ActiveCfg = Debug|x64 - {A3D9E589-CD2F-4427-804E-3A5865CA3C17}.Debug|x64.Build.0 = Debug|x64 - {A3D9E589-CD2F-4427-804E-3A5865CA3C17}.Debug|x86.ActiveCfg = Debug|Win32 - {A3D9E589-CD2F-4427-804E-3A5865CA3C17}.Debug|x86.Build.0 = Debug|Win32 - {A3D9E589-CD2F-4427-804E-3A5865CA3C17}.Release|x64.ActiveCfg = Release|x64 - {A3D9E589-CD2F-4427-804E-3A5865CA3C17}.Release|x64.Build.0 = Release|x64 - {A3D9E589-CD2F-4427-804E-3A5865CA3C17}.Release|x86.ActiveCfg = Release|Win32 - {A3D9E589-CD2F-4427-804E-3A5865CA3C17}.Release|x86.Build.0 = Release|Win32 - {AC905C95-1311-4798-8576-F1A08CCE259F}.Debug|x64.ActiveCfg = Debug|x64 - {AC905C95-1311-4798-8576-F1A08CCE259F}.Debug|x64.Build.0 = Debug|x64 - {AC905C95-1311-4798-8576-F1A08CCE259F}.Debug|x86.ActiveCfg = Debug|Win32 - {AC905C95-1311-4798-8576-F1A08CCE259F}.Debug|x86.Build.0 = Debug|Win32 - {AC905C95-1311-4798-8576-F1A08CCE259F}.Release|x64.ActiveCfg = Release|x64 - {AC905C95-1311-4798-8576-F1A08CCE259F}.Release|x64.Build.0 = Release|x64 - {AC905C95-1311-4798-8576-F1A08CCE259F}.Release|x86.ActiveCfg = Release|Win32 - {AC905C95-1311-4798-8576-F1A08CCE259F}.Release|x86.Build.0 = Release|Win32 - {BC2385D0-C79C-4E42-989E-6B2EE268F2D9}.Debug|x64.ActiveCfg = Debug|x64 - {BC2385D0-C79C-4E42-989E-6B2EE268F2D9}.Debug|x64.Build.0 = Debug|x64 - {BC2385D0-C79C-4E42-989E-6B2EE268F2D9}.Debug|x86.ActiveCfg = Debug|Win32 - {BC2385D0-C79C-4E42-989E-6B2EE268F2D9}.Debug|x86.Build.0 = Debug|Win32 - {BC2385D0-C79C-4E42-989E-6B2EE268F2D9}.Release|x64.ActiveCfg = Release|x64 - {BC2385D0-C79C-4E42-989E-6B2EE268F2D9}.Release|x64.Build.0 = Release|x64 - {BC2385D0-C79C-4E42-989E-6B2EE268F2D9}.Release|x86.ActiveCfg = Release|Win32 - {BC2385D0-C79C-4E42-989E-6B2EE268F2D9}.Release|x86.Build.0 = Release|Win32 - {162FD21D-EA17-448A-9892-CAD62D6849DB}.Debug|x64.ActiveCfg = Debug|x64 - {162FD21D-EA17-448A-9892-CAD62D6849DB}.Debug|x64.Build.0 = Debug|x64 - {162FD21D-EA17-448A-9892-CAD62D6849DB}.Debug|x86.ActiveCfg = Debug|Win32 - {162FD21D-EA17-448A-9892-CAD62D6849DB}.Debug|x86.Build.0 = Debug|Win32 - {162FD21D-EA17-448A-9892-CAD62D6849DB}.Release|x64.ActiveCfg = Release|x64 - {162FD21D-EA17-448A-9892-CAD62D6849DB}.Release|x64.Build.0 = Release|x64 - {162FD21D-EA17-448A-9892-CAD62D6849DB}.Release|x86.ActiveCfg = Release|Win32 - {162FD21D-EA17-448A-9892-CAD62D6849DB}.Release|x86.Build.0 = Release|Win32 - EndGlobalSection - GlobalSection(SolutionProperties) = preSolution - HideSolutionNode = FALSE - EndGlobalSection - GlobalSection(ExtensibilityGlobals) = postSolution - SolutionGuid = {CA7CCD5A-809A-44A8-AAC8-BA018D0B1596} - EndGlobalSection -EndGlobal diff --git a/tool/libwinhook/libwinhook/libwinhook.vcxproj.filters b/tool/libwinhook/libwinhook/libwinhook.vcxproj.filters deleted file mode 100644 index 05b64f4..0000000 --- a/tool/libwinhook/libwinhook/libwinhook.vcxproj.filters +++ /dev/null @@ -1,22 +0,0 @@ - - - - - {4FC737F1-C7A5-4376-A066-2A32D752A2FF} - cpp;c;cc;cxx;c++;cppm;ixx;def;odl;idl;hpj;bat;asm;asmx - - - {93995380-89BD-4b04-88EB-625FBE52EBFB} - h;hh;hpp;hxx;h++;hm;inl;inc;ipp;xsd - - - {67DA6AB6-F800-4c08-8B7A-83BB121AAD01} - rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav;mfcribbon-ms - - - - - 源文件 - - - \ No newline at end of file diff --git a/tool/libwinhook/libwinhook/libwinhook.vcxproj.user b/tool/libwinhook/libwinhook/libwinhook.vcxproj.user deleted file mode 100644 index 0f14913..0000000 --- a/tool/libwinhook/libwinhook/libwinhook.vcxproj.user +++ /dev/null @@ -1,4 +0,0 @@ - - - - \ No newline at end of file diff --git a/tool/libwinhook/test/test.vcxproj.filters b/tool/libwinhook/test/test.vcxproj.filters deleted file mode 100644 index 050169e..0000000 --- a/tool/libwinhook/test/test.vcxproj.filters +++ /dev/null @@ -1,22 +0,0 @@ - - - - - {4FC737F1-C7A5-4376-A066-2A32D752A2FF} - cpp;c;cc;cxx;c++;cppm;ixx;def;odl;idl;hpj;bat;asm;asmx - - - {93995380-89BD-4b04-88EB-625FBE52EBFB} - h;hh;hpp;hxx;h++;hm;inl;inc;ipp;xsd - - - {67DA6AB6-F800-4c08-8B7A-83BB121AAD01} - rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav;mfcribbon-ms - - - - - 源文件 - - - \ No newline at end of file diff --git a/tool/libwinhook/test/test.vcxproj.user b/tool/libwinhook/test/test.vcxproj.user deleted file mode 100644 index 894de0c..0000000 --- a/tool/libwinhook/test/test.vcxproj.user +++ /dev/null @@ -1,19 +0,0 @@ - - - - $(TargetDir) - WindowsLocalDebugger - - - $(TargetDir) - WindowsLocalDebugger - - - $(TargetDir) - WindowsLocalDebugger - - - $(TargetDir) - WindowsLocalDebugger - - \ No newline at end of file diff --git a/tool/libwinhook/test_hello/Resource.h b/tool/libwinhook/test_hello/Resource.h deleted file mode 100644 index 9b25361..0000000 --- a/tool/libwinhook/test_hello/Resource.h +++ /dev/null @@ -1,30 +0,0 @@ -//{{NO_DEPENDENCIES}} -// Microsoft Visual C++ 生成的包含文件。 -// 使用者 hello.rc - -#define IDS_APP_TITLE 103 - -#define IDR_MAINFRAME 128 -#define IDD_HELLO_DIALOG 102 -#define IDD_ABOUTBOX 103 -#define IDM_ABOUT 104 -#define IDM_EXIT 105 -#define IDI_HELLO 107 -#define IDI_SMALL 108 -#define IDC_HELLO 109 -#define IDC_MYICON 2 -#ifndef IDC_STATIC -#define IDC_STATIC -1 -#endif -// 新对象的下一组默认值 -// -#ifdef APSTUDIO_INVOKED -#ifndef APSTUDIO_READONLY_SYMBOLS - -#define _APS_NO_MFC 130 -#define _APS_NEXT_RESOURCE_VALUE 129 -#define _APS_NEXT_COMMAND_VALUE 32771 -#define _APS_NEXT_CONTROL_VALUE 1000 -#define _APS_NEXT_SYMED_VALUE 110 -#endif -#endif diff --git a/tool/libwinhook/test_hello/framework.h b/tool/libwinhook/test_hello/framework.h deleted file mode 100644 index 039a85c..0000000 --- a/tool/libwinhook/test_hello/framework.h +++ /dev/null @@ -1,15 +0,0 @@ -// header.h: 标准系统包含文件的包含文件, -// 或特定于项目的包含文件 -// - -#pragma once - -#include "targetver.h" -#define WIN32_LEAN_AND_MEAN // 从 Windows 头文件中排除极少使用的内容 -// Windows 头文件 -#include -// C 运行时头文件 -#include -#include -#include -#include diff --git a/tool/libwinhook/test_hello/hello.aps b/tool/libwinhook/test_hello/hello.aps deleted file mode 100644 index 6c2faff..0000000 Binary files a/tool/libwinhook/test_hello/hello.aps and /dev/null differ diff --git a/tool/libwinhook/test_hello/hello.cpp b/tool/libwinhook/test_hello/hello.cpp deleted file mode 100644 index a17ff6c..0000000 --- a/tool/libwinhook/test_hello/hello.cpp +++ /dev/null @@ -1,180 +0,0 @@ -// hello.cpp : 定义应用程序的入口点。 -// - -#include "framework.h" -#include "hello.h" - -#define MAX_LOADSTRING 100 - -// 全局变量: -HINSTANCE hInst; // 当前实例 -WCHAR szTitle[MAX_LOADSTRING]; // 标题栏文本 -WCHAR szWindowClass[MAX_LOADSTRING]; // 主窗口类名 - -// 此代码模块中包含的函数的前向声明: -ATOM MyRegisterClass(HINSTANCE hInstance); -BOOL InitInstance(HINSTANCE, int); -LRESULT CALLBACK WndProc(HWND, UINT, WPARAM, LPARAM); -INT_PTR CALLBACK About(HWND, UINT, WPARAM, LPARAM); - -int APIENTRY wWinMain(_In_ HINSTANCE hInstance, - _In_opt_ HINSTANCE hPrevInstance, - _In_ LPWSTR lpCmdLine, - _In_ int nCmdShow) -{ - UNREFERENCED_PARAMETER(hPrevInstance); - UNREFERENCED_PARAMETER(lpCmdLine); - - // TODO: 在此处放置代码。 - - // 初始化全局字符串 - LoadStringW(hInstance, IDS_APP_TITLE, szTitle, MAX_LOADSTRING); - LoadStringW(hInstance, IDC_HELLO, szWindowClass, MAX_LOADSTRING); - MyRegisterClass(hInstance); - - // 执行应用程序初始化: - if (!InitInstance (hInstance, nCmdShow)) - { - return FALSE; - } - - HACCEL hAccelTable = LoadAccelerators(hInstance, MAKEINTRESOURCE(IDC_HELLO)); - - MSG msg; - - // 主消息循环: - while (GetMessage(&msg, nullptr, 0, 0)) - { - if (!TranslateAccelerator(msg.hwnd, hAccelTable, &msg)) - { - TranslateMessage(&msg); - DispatchMessage(&msg); - } - } - - return (int) msg.wParam; -} - - - -// -// 函数: MyRegisterClass() -// -// 目标: 注册窗口类。 -// -ATOM MyRegisterClass(HINSTANCE hInstance) -{ - WNDCLASSEXW wcex; - - wcex.cbSize = sizeof(WNDCLASSEX); - - wcex.style = CS_HREDRAW | CS_VREDRAW; - wcex.lpfnWndProc = WndProc; - wcex.cbClsExtra = 0; - wcex.cbWndExtra = 0; - wcex.hInstance = hInstance; - wcex.hIcon = LoadIcon(hInstance, MAKEINTRESOURCE(IDI_HELLO)); - wcex.hCursor = LoadCursor(nullptr, IDC_ARROW); - wcex.hbrBackground = (HBRUSH)(COLOR_WINDOW+1); - wcex.lpszMenuName = MAKEINTRESOURCEW(IDC_HELLO); - wcex.lpszClassName = szWindowClass; - wcex.hIconSm = LoadIcon(wcex.hInstance, MAKEINTRESOURCE(IDI_SMALL)); - - return RegisterClassExW(&wcex); -} - -// -// 函数: InitInstance(HINSTANCE, int) -// -// 目标: 保存实例句柄并创建主窗口 -// -// 注释: -// -// 在此函数中,我们在全局变量中保存实例句柄并 -// 创建和显示主程序窗口。 -// -BOOL InitInstance(HINSTANCE hInstance, int nCmdShow) -{ - hInst = hInstance; // 将实例句柄存储在全局变量中 - - HWND hWnd = CreateWindowW(szWindowClass, szTitle, WS_OVERLAPPEDWINDOW, - CW_USEDEFAULT, 0, CW_USEDEFAULT, 0, nullptr, nullptr, hInstance, nullptr); - - if (!hWnd) - { - return FALSE; - } - - ShowWindow(hWnd, nCmdShow); - UpdateWindow(hWnd); - - return TRUE; -} - -// -// 函数: WndProc(HWND, UINT, WPARAM, LPARAM) -// -// 目标: 处理主窗口的消息。 -// -// WM_COMMAND - 处理应用程序菜单 -// WM_PAINT - 绘制主窗口 -// WM_DESTROY - 发送退出消息并返回 -// -// -LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam) -{ - switch (message) - { - case WM_COMMAND: - { - int wmId = LOWORD(wParam); - // 分析菜单选择: - switch (wmId) - { - case IDM_ABOUT: - DialogBox(hInst, MAKEINTRESOURCE(IDD_ABOUTBOX), hWnd, About); - break; - case IDM_EXIT: - DestroyWindow(hWnd); - break; - default: - return DefWindowProc(hWnd, message, wParam, lParam); - } - } - break; - case WM_PAINT: - { - PAINTSTRUCT ps; - HDC hdc = BeginPaint(hWnd, &ps); - // TODO: 在此处添加使用 hdc 的任何绘图代码... - EndPaint(hWnd, &ps); - } - break; - case WM_DESTROY: - PostQuitMessage(0); - break; - default: - return DefWindowProc(hWnd, message, wParam, lParam); - } - return 0; -} - -// “关于”框的消息处理程序。 -INT_PTR CALLBACK About(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam) -{ - UNREFERENCED_PARAMETER(lParam); - switch (message) - { - case WM_INITDIALOG: - return (INT_PTR)TRUE; - - case WM_COMMAND: - if (LOWORD(wParam) == IDOK || LOWORD(wParam) == IDCANCEL) - { - EndDialog(hDlg, LOWORD(wParam)); - return (INT_PTR)TRUE; - } - break; - } - return (INT_PTR)FALSE; -} diff --git a/tool/libwinhook/test_hello/hello.h b/tool/libwinhook/test_hello/hello.h deleted file mode 100644 index e60f2eb..0000000 --- a/tool/libwinhook/test_hello/hello.h +++ /dev/null @@ -1,3 +0,0 @@ -#pragma once - -#include "resource.h" diff --git a/tool/libwinhook/test_hello/hello.ico b/tool/libwinhook/test_hello/hello.ico deleted file mode 100644 index b3ec03b..0000000 Binary files a/tool/libwinhook/test_hello/hello.ico and /dev/null differ diff --git a/tool/libwinhook/test_hello/hello.rc b/tool/libwinhook/test_hello/hello.rc deleted file mode 100644 index 20b18e1..0000000 Binary files a/tool/libwinhook/test_hello/hello.rc and /dev/null differ diff --git a/tool/libwinhook/test_hello/small.ico b/tool/libwinhook/test_hello/small.ico deleted file mode 100644 index b3ec03b..0000000 Binary files a/tool/libwinhook/test_hello/small.ico and /dev/null differ diff --git a/tool/libwinhook/test_hello/targetver.h b/tool/libwinhook/test_hello/targetver.h deleted file mode 100644 index e5037ff..0000000 --- a/tool/libwinhook/test_hello/targetver.h +++ /dev/null @@ -1,6 +0,0 @@ -#pragma once - -// // 包含 SDKDDKVer.h 可定义可用的最高版本的 Windows 平台。 -// 如果希望为之前的 Windows 平台构建应用程序,在包含 SDKDDKVer.h 之前请先包含 WinSDKVer.h 并 -// 将 _WIN32_WINNT 宏设置为想要支持的平台。 -#include diff --git a/tool/libwinhook/test_hello/test_hello.vcxproj b/tool/libwinhook/test_hello/test_hello.vcxproj deleted file mode 100644 index 7e78ef6..0000000 --- a/tool/libwinhook/test_hello/test_hello.vcxproj +++ /dev/null @@ -1,170 +0,0 @@ - - - - - Debug - Win32 - - - Release - Win32 - - - Debug - x64 - - - Release - x64 - - - - 16.0 - Win32Proj - {bc2385d0-c79c-4e42-989e-6b2ee268f2d9} - test_hello - 7.0 - - - - Application - true - v141_xp - Unicode - - - Application - false - v141_xp - true - Unicode - - - Application - true - v141_xp - Unicode - - - Application - false - v141_xp - true - Unicode - - - - - - - - - - - - - - - - - - - - - true - hello - - - false - hello - - - true - hello - - - false - hello - - - - Level3 - true - WIN32;_DEBUG;_WINDOWS;%(PreprocessorDefinitions) - true - MultiThreaded - - - Windows - true - - - - - Level3 - true - true - true - WIN32;NDEBUG;_WINDOWS;%(PreprocessorDefinitions) - true - MultiThreaded - - - Windows - true - true - true - - - - - Level3 - true - _DEBUG;_WINDOWS;%(PreprocessorDefinitions) - true - MultiThreaded - - - Windows - true - 5.01 - - - - - Level3 - true - true - true - NDEBUG;_WINDOWS;%(PreprocessorDefinitions) - true - MultiThreaded - - - Windows - true - true - true - 5.01 - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/tool/libwinhook/test_hello/test_hello.vcxproj.filters b/tool/libwinhook/test_hello/test_hello.vcxproj.filters deleted file mode 100644 index d43bff5..0000000 --- a/tool/libwinhook/test_hello/test_hello.vcxproj.filters +++ /dev/null @@ -1,49 +0,0 @@ - - - - - {4FC737F1-C7A5-4376-A066-2A32D752A2FF} - cpp;c;cc;cxx;c++;cppm;ixx;def;odl;idl;hpj;bat;asm;asmx - - - {93995380-89BD-4b04-88EB-625FBE52EBFB} - h;hh;hpp;hxx;h++;hm;inl;inc;ipp;xsd - - - {67DA6AB6-F800-4c08-8B7A-83BB121AAD01} - rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav;mfcribbon-ms - - - - - 头文件 - - - 头文件 - - - 头文件 - - - 头文件 - - - - - 源文件 - - - - - 资源文件 - - - - - 资源文件 - - - 资源文件 - - - \ No newline at end of file diff --git a/tool/libwinhook/test_hello/test_hello.vcxproj.user b/tool/libwinhook/test_hello/test_hello.vcxproj.user deleted file mode 100644 index 0f14913..0000000 --- a/tool/libwinhook/test_hello/test_hello.vcxproj.user +++ /dev/null @@ -1,4 +0,0 @@ - - - - \ No newline at end of file diff --git a/tool/libwinhook/test_hellodll/test_hellodll.vcxproj.filters b/tool/libwinhook/test_hellodll/test_hellodll.vcxproj.filters deleted file mode 100644 index b836220..0000000 --- a/tool/libwinhook/test_hellodll/test_hellodll.vcxproj.filters +++ /dev/null @@ -1,22 +0,0 @@ - - - - - {4FC737F1-C7A5-4376-A066-2A32D752A2FF} - cpp;c;cc;cxx;c++;cppm;ixx;def;odl;idl;hpj;bat;asm;asmx - - - {93995380-89BD-4b04-88EB-625FBE52EBFB} - h;hh;hpp;hxx;h++;hm;inl;inc;ipp;xsd - - - {67DA6AB6-F800-4c08-8B7A-83BB121AAD01} - rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav;mfcribbon-ms - - - - - 源文件 - - - \ No newline at end of file diff --git a/tool/libwinhook/test_hellodll/test_hellodll.vcxproj.user b/tool/libwinhook/test_hellodll/test_hellodll.vcxproj.user deleted file mode 100644 index 0f14913..0000000 --- a/tool/libwinhook/test_hellodll/test_hellodll.vcxproj.user +++ /dev/null @@ -1,4 +0,0 @@ - - - - \ No newline at end of file diff --git a/tool/libwinpe/libwinpe.sln b/tool/libwinpe/libwinpe.sln deleted file mode 100644 index b0051ea..0000000 --- a/tool/libwinpe/libwinpe.sln +++ /dev/null @@ -1,41 +0,0 @@ - -Microsoft Visual Studio Solution File, Format Version 12.00 -# Visual Studio Version 16 -VisualStudioVersion = 16.0.31613.86 -MinimumVisualStudioVersion = 10.0.40219.1 -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "libwinpe", "libwinpe\libwinpe.vcxproj", "{F5BA2655-5138-436C-87FE-8EF75AD1A2CE}" -EndProject -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "test", "test\test.vcxproj", "{E2B4EBF4-169A-473F-936E-D95DA3E861A3}" -EndProject -Global - GlobalSection(SolutionConfigurationPlatforms) = preSolution - Debug|x64 = Debug|x64 - Debug|x86 = Debug|x86 - Release|x64 = Release|x64 - Release|x86 = Release|x86 - EndGlobalSection - GlobalSection(ProjectConfigurationPlatforms) = postSolution - {F5BA2655-5138-436C-87FE-8EF75AD1A2CE}.Debug|x64.ActiveCfg = Debug|x64 - {F5BA2655-5138-436C-87FE-8EF75AD1A2CE}.Debug|x64.Build.0 = Debug|x64 - {F5BA2655-5138-436C-87FE-8EF75AD1A2CE}.Debug|x86.ActiveCfg = Debug|Win32 - {F5BA2655-5138-436C-87FE-8EF75AD1A2CE}.Debug|x86.Build.0 = Debug|Win32 - {F5BA2655-5138-436C-87FE-8EF75AD1A2CE}.Release|x64.ActiveCfg = Release|x64 - {F5BA2655-5138-436C-87FE-8EF75AD1A2CE}.Release|x64.Build.0 = Release|x64 - {F5BA2655-5138-436C-87FE-8EF75AD1A2CE}.Release|x86.ActiveCfg = Release|Win32 - {F5BA2655-5138-436C-87FE-8EF75AD1A2CE}.Release|x86.Build.0 = Release|Win32 - {E2B4EBF4-169A-473F-936E-D95DA3E861A3}.Debug|x64.ActiveCfg = Debug|x64 - {E2B4EBF4-169A-473F-936E-D95DA3E861A3}.Debug|x64.Build.0 = Debug|x64 - {E2B4EBF4-169A-473F-936E-D95DA3E861A3}.Debug|x86.ActiveCfg = Debug|Win32 - {E2B4EBF4-169A-473F-936E-D95DA3E861A3}.Debug|x86.Build.0 = Debug|Win32 - {E2B4EBF4-169A-473F-936E-D95DA3E861A3}.Release|x64.ActiveCfg = Release|x64 - {E2B4EBF4-169A-473F-936E-D95DA3E861A3}.Release|x64.Build.0 = Release|x64 - {E2B4EBF4-169A-473F-936E-D95DA3E861A3}.Release|x86.ActiveCfg = Release|Win32 - {E2B4EBF4-169A-473F-936E-D95DA3E861A3}.Release|x86.Build.0 = Release|Win32 - EndGlobalSection - GlobalSection(SolutionProperties) = preSolution - HideSolutionNode = FALSE - EndGlobalSection - GlobalSection(ExtensibilityGlobals) = postSolution - SolutionGuid = {99F1140B-A1EE-4793-AC62-4F3138CC5281} - EndGlobalSection -EndGlobal diff --git a/tool/libwinpe/libwinpe/libwinpe.vcxproj b/tool/libwinpe/libwinpe/libwinpe.vcxproj deleted file mode 100644 index 82c3d49..0000000 --- a/tool/libwinpe/libwinpe/libwinpe.vcxproj +++ /dev/null @@ -1,162 +0,0 @@ - - - - - Debug - Win32 - - - Release - Win32 - - - Debug - x64 - - - Release - x64 - - - - - - - 16.0 - Win32Proj - {f5ba2655-5138-436c-87fe-8ef75ad1a2ce} - libwinpe - - - - DynamicLibrary - true - v141_xp - MultiByte - - - DynamicLibrary - false - v141_xp - true - MultiByte - - - DynamicLibrary - true - v141_xp - MultiByte - - - DynamicLibrary - false - v141_xp - true - MultiByte - - - - - - - - - - - - - - - - - - - - - false - - - false - - - false - - - false - - - - Level3 - true - _CRT_SECURE_NO_WARNINGS;WIN32;_DEBUG;_CONSOLE;%(PreprocessorDefinitions)_CRT_SECURE_NO_WARNINGS - true - ./../../../include;%(AdditionalIncludeDirectories) - MultiThreaded - - - Console - true - 5.01 - libwinpe.def - - - - - Level3 - true - true - true - _CRT_SECURE_NO_WARNINGS;WIN32;NDEBUG;_CONSOLE;%(PreprocessorDefinitions)_CRT_SECURE_NO_WARNINGS - true - ./../../../include;%(AdditionalIncludeDirectories) - MultiThreaded - - - Console - true - true - true - 5.01 - libwinpe.def - - - - - Level3 - true - _CRT_SECURE_NO_WARNINGS;WINPE_NOASM;_DEBUG;_CONSOLE;%(PreprocessorDefinitions)_CRT_SECURE_NO_WARNINGS - true - ./../../../include;%(AdditionalIncludeDirectories) - MultiThreaded - - - Console - true - 5.01 - libwinpe.def - - - - - Level3 - true - true - true - _CRT_SECURE_NO_WARNINGS;WINPE_NOASM;NDEBUG;_CONSOLE;%(PreprocessorDefinitions)_CRT_SECURE_NO_WARNINGS - true - ./../../../include;%(AdditionalIncludeDirectories) - MultiThreaded - - - Console - true - true - true - 5.01 - libwinpe.def - - - - - - \ No newline at end of file diff --git a/tool/libwinpe/libwinpe/libwinpe.vcxproj.filters b/tool/libwinpe/libwinpe/libwinpe.vcxproj.filters deleted file mode 100644 index 5b9b305..0000000 --- a/tool/libwinpe/libwinpe/libwinpe.vcxproj.filters +++ /dev/null @@ -1,22 +0,0 @@ - - - - - {4FC737F1-C7A5-4376-A066-2A32D752A2FF} - cpp;c;cc;cxx;c++;cppm;ixx;def;odl;idl;hpj;bat;asm;asmx - - - {93995380-89BD-4b04-88EB-625FBE52EBFB} - h;hh;hpp;hxx;h++;hm;inl;inc;ipp;xsd - - - {67DA6AB6-F800-4c08-8B7A-83BB121AAD01} - rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav;mfcribbon-ms - - - - - 源文件 - - - \ No newline at end of file diff --git a/tool/libwinpe/libwinpe/libwinpe.vcxproj.user b/tool/libwinpe/libwinpe/libwinpe.vcxproj.user deleted file mode 100644 index 0f14913..0000000 --- a/tool/libwinpe/libwinpe/libwinpe.vcxproj.user +++ /dev/null @@ -1,4 +0,0 @@ - - - - \ No newline at end of file diff --git a/tool/libwinpe/test/test.c b/tool/libwinpe/test/test.c deleted file mode 100644 index 453f4bb..0000000 --- a/tool/libwinpe/test/test.c +++ /dev/null @@ -1,32 +0,0 @@ -#include -#include -#include -#define WINPE_IMPLEMENTATION -#define WINPE_NOASM -#include "winpe.h" - -void test_findexpcrc() -{ - HMODULE kernel32 = (HMODULE)winpe_findkernel32(); - assert(GetModuleHandleA("kernel32") == kernel32); - uint32_t LoadLibraryA_crc32 = _winpeinl_crc32("LoadLibraryA", 12); - assert(LoadLibraryA_crc32 == 0x3fc1bd8d); - assert(winpe_memfindexpcrc32(kernel32, LoadLibraryA_crc32) - == GetProcAddress(kernel32, "LoadLibraryA")); -} - -void test_getfunc(HMODULE hmod, const char* funcname) -{ - size_t expva = (size_t)GetProcAddress(hmod, funcname); - size_t exprva = (size_t)winpe_memfindexp(hmod, funcname) - (size_t)hmod; - void* func2 = winpe_memGetProcAddress(hmod, funcname); - assert(exprva != 0 && func2 == expva); - printf("test_getfunc %p %s passed!\n", hmod, funcname); -} - -int main(int argc, char* argv[]) -{ - test_getfunc(LoadLibraryA("kernel32.dll"), "GetProcessMitigationPolicy"); - test_findexpcrc(); - return 0; -} \ No newline at end of file diff --git a/tool/libwinpe/test/test.vcxproj.filters b/tool/libwinpe/test/test.vcxproj.filters deleted file mode 100644 index 27ddc33..0000000 --- a/tool/libwinpe/test/test.vcxproj.filters +++ /dev/null @@ -1,22 +0,0 @@ - - - - - {4FC737F1-C7A5-4376-A066-2A32D752A2FF} - cpp;c;cc;cxx;c++;cppm;ixx;def;odl;idl;hpj;bat;asm;asmx - - - {93995380-89BD-4b04-88EB-625FBE52EBFB} - h;hh;hpp;hxx;h++;hm;inl;inc;ipp;xsd - - - {67DA6AB6-F800-4c08-8B7A-83BB121AAD01} - rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav;mfcribbon-ms - - - - - 源文件 - - - \ No newline at end of file diff --git a/tool/libwinpe/test/test.vcxproj.user b/tool/libwinpe/test/test.vcxproj.user deleted file mode 100644 index 0f14913..0000000 --- a/tool/libwinpe/test/test.vcxproj.user +++ /dev/null @@ -1,4 +0,0 @@ - - - - \ No newline at end of file diff --git a/tool/pybuildbase_env.bat b/tool/pybuildbase_env.bat deleted file mode 100644 index 8419f1e..0000000 --- a/tool/pybuildbase_env.bat +++ /dev/null @@ -1,17 +0,0 @@ -:: by_pybase_env envdir runbatpath args -@echo off -set ENVDIR=%1 -set RUNBATPATH=%2 -SET ARGS=%3 %4 %5 %6 %7 %8 %9 -if not exist %ENVDIR% ( - mkdir %ENVDIR% - pushd %ENVDIR% - python -m venv %ENVDIR% - cd /d %ENVDIR%\Scripts - python -m pip install pyinstaller - python -m pip install nuitka - popd -) -pushd %ENVDIR% -call %RUNBATPATH% %ARGS% -popd \ No newline at end of file