├── .gitattributes ├── .gitignore ├── LICENSE ├── README.md ├── mapper.sln └── mapper ├── api_set.cpp ├── api_set.hpp ├── binary_file.cpp ├── binary_file.hpp ├── cast.hpp ├── dllmain_call_x64.asm ├── dllmain_hijack_x64.asm ├── executors.cpp ├── executors.hpp ├── loadlibrary.cpp ├── loadlibrary.hpp ├── logger.cpp ├── logger.hpp ├── main.cpp ├── maker.hpp ├── manualmapper.cpp ├── manualmapper.hpp ├── map_context.cpp ├── map_context.hpp ├── mapper.vcxproj ├── mapper.vcxproj.filters ├── mapper.vcxproj[Conflict].filters ├── memory_section.hpp ├── ntdll.cpp ├── ntdll.hpp ├── pe_section.hpp ├── portable_executable.cpp ├── portable_executable.hpp ├── process.cpp ├── process.hpp ├── safe_handle.hpp ├── safe_memory.hpp ├── shellcode.cpp ├── shellcode.hpp ├── thread.cpp ├── thread.hpp └── transformer.hpp /.gitattributes: -------------------------------------------------------------------------------- 1 | ############################################################################### 2 | # Set default behavior to automatically normalize line endings. 3 | ############################################################################### 4 | * text=auto 5 | 6 | ############################################################################### 7 | # Set default behavior for command prompt diff. 8 | # 9 | # This is need for earlier builds of msysgit that does not have it on by 10 | # default for csharp files. 11 | # Note: This is only used by command line 12 | ############################################################################### 13 | #*.cs diff=csharp 14 | 15 | ############################################################################### 16 | # Set the merge driver for project and solution files 17 | # 18 | # Merging from the command prompt will add diff markers to the files if there 19 | # are conflicts (Merging from VS is not affected by the settings below, in VS 20 | # the diff markers are never inserted). Diff markers may cause the following 21 | # file extensions to fail to load in VS. An alternative would be to treat 22 | # these files as binary and thus will always conflict and require user 23 | # intervention with every merge. To do so, just uncomment the entries below 24 | ############################################################################### 25 | #*.sln merge=binary 26 | #*.csproj merge=binary 27 | #*.vbproj merge=binary 28 | #*.vcxproj merge=binary 29 | #*.vcproj merge=binary 30 | #*.dbproj merge=binary 31 | #*.fsproj merge=binary 32 | #*.lsproj merge=binary 33 | #*.wixproj merge=binary 34 | #*.modelproj merge=binary 35 | #*.sqlproj merge=binary 36 | #*.wwaproj merge=binary 37 | 38 | ############################################################################### 39 | # behavior for image files 40 | # 41 | # image files are treated as binary by default. 42 | ############################################################################### 43 | #*.jpg binary 44 | #*.png binary 45 | #*.gif binary 46 | 47 | ############################################################################### 48 | # diff behavior for common document formats 49 | # 50 | # Convert binary document formats to text before diffing them. This feature 51 | # is only available from the command line. Turn it on by uncommenting the 52 | # entries below. 53 | ############################################################################### 54 | #*.doc diff=astextplain 55 | #*.DOC diff=astextplain 56 | #*.docx diff=astextplain 57 | #*.DOCX diff=astextplain 58 | #*.dot diff=astextplain 59 | #*.DOT diff=astextplain 60 | #*.pdf diff=astextplain 61 | #*.PDF diff=astextplain 62 | #*.rtf diff=astextplain 63 | #*.RTF diff=astextplain 64 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | ## Ignore Visual Studio temporary files, build results, and 2 | ## files generated by popular Visual Studio add-ons. 3 | 4 | # User-specific files 5 | *.suo 6 | *.user 7 | *.userosscache 8 | *.sln.docstates 9 | 10 | # User-specific files (MonoDevelop/Xamarin Studio) 11 | *.userprefs 12 | 13 | # Build results 14 | [Dd]ebug/ 15 | [Dd]ebugPublic/ 16 | [Rr]elease/ 17 | [Rr]eleases/ 18 | x64/ 19 | x86/ 20 | bld/ 21 | [Bb]in/ 22 | [Oo]bj/ 23 | [Ll]og/ 24 | 25 | # Visual Studio 2015 cache/options directory 26 | .vs/ 27 | # Uncomment if you have tasks that create the project's static files in wwwroot 28 | #wwwroot/ 29 | 30 | # MSTest test Results 31 | [Tt]est[Rr]esult*/ 32 | [Bb]uild[Ll]og.* 33 | 34 | # NUNIT 35 | *.VisualState.xml 36 | TestResult.xml 37 | 38 | # Build Results of an ATL Project 39 | [Dd]ebugPS/ 40 | [Rr]eleasePS/ 41 | dlldata.c 42 | 43 | # DNX 44 | project.lock.json 45 | project.fragment.lock.json 46 | artifacts/ 47 | 48 | *_i.c 49 | *_p.c 50 | *_i.h 51 | *.ilk 52 | *.meta 53 | *.obj 54 | *.pch 55 | *.pdb 56 | *.pgc 57 | *.pgd 58 | *.rsp 59 | *.sbr 60 | *.tlb 61 | *.tli 62 | *.tlh 63 | *.tmp 64 | *.tmp_proj 65 | *.log 66 | *.vspscc 67 | *.vssscc 68 | .builds 69 | *.pidb 70 | *.svclog 71 | *.scc 72 | 73 | # Chutzpah Test files 74 | _Chutzpah* 75 | 76 | # Visual C++ cache files 77 | ipch/ 78 | *.aps 79 | *.ncb 80 | *.opendb 81 | *.opensdf 82 | *.sdf 83 | *.cachefile 84 | *.VC.db 85 | *.VC.VC.opendb 86 | 87 | # Visual Studio profiler 88 | *.psess 89 | *.vsp 90 | *.vspx 91 | *.sap 92 | 93 | # TFS 2012 Local Workspace 94 | $tf/ 95 | 96 | # Guidance Automation Toolkit 97 | *.gpState 98 | 99 | # ReSharper is a .NET coding add-in 100 | _ReSharper*/ 101 | *.[Rr]e[Ss]harper 102 | *.DotSettings.user 103 | 104 | # JustCode is a .NET coding add-in 105 | .JustCode 106 | 107 | # TeamCity is a build add-in 108 | _TeamCity* 109 | 110 | # DotCover is a Code Coverage Tool 111 | *.dotCover 112 | 113 | # NCrunch 114 | _NCrunch_* 115 | .*crunch*.local.xml 116 | nCrunchTemp_* 117 | 118 | # MightyMoose 119 | *.mm.* 120 | AutoTest.Net/ 121 | 122 | # Web workbench (sass) 123 | .sass-cache/ 124 | 125 | # Installshield output folder 126 | [Ee]xpress/ 127 | 128 | # DocProject is a documentation generator add-in 129 | DocProject/buildhelp/ 130 | DocProject/Help/*.HxT 131 | DocProject/Help/*.HxC 132 | DocProject/Help/*.hhc 133 | DocProject/Help/*.hhk 134 | DocProject/Help/*.hhp 135 | DocProject/Help/Html2 136 | DocProject/Help/html 137 | 138 | # Click-Once directory 139 | publish/ 140 | 141 | # Publish Web Output 142 | *.[Pp]ublish.xml 143 | *.azurePubxml 144 | # TODO: Comment the next line if you want to checkin your web deploy settings 145 | # but database connection strings (with potential passwords) will be unencrypted 146 | #*.pubxml 147 | *.publishproj 148 | 149 | # Microsoft Azure Web App publish settings. Comment the next line if you want to 150 | # checkin your Azure Web App publish settings, but sensitive information contained 151 | # in these scripts will be unencrypted 152 | PublishScripts/ 153 | 154 | # NuGet Packages 155 | *.nupkg 156 | # The packages folder can be ignored because of Package Restore 157 | **/packages/* 158 | # except build/, which is used as an MSBuild target. 159 | !**/packages/build/ 160 | # Uncomment if necessary however generally it will be regenerated when needed 161 | #!**/packages/repositories.config 162 | # NuGet v3's project.json files produces more ignoreable files 163 | *.nuget.props 164 | *.nuget.targets 165 | 166 | # Microsoft Azure Build Output 167 | csx/ 168 | *.build.csdef 169 | 170 | # Microsoft Azure Emulator 171 | ecf/ 172 | rcf/ 173 | 174 | # Windows Store app package directories and files 175 | AppPackages/ 176 | BundleArtifacts/ 177 | Package.StoreAssociation.xml 178 | _pkginfo.txt 179 | 180 | # Visual Studio cache files 181 | # files ending in .cache can be ignored 182 | *.[Cc]ache 183 | # but keep track of directories ending in .cache 184 | !*.[Cc]ache/ 185 | 186 | # Others 187 | ClientBin/ 188 | ~$* 189 | *~ 190 | *.dbmdl 191 | *.dbproj.schemaview 192 | *.jfm 193 | *.pfx 194 | *.publishsettings 195 | node_modules/ 196 | orleans.codegen.cs 197 | 198 | # Since there are multiple workflows, uncomment next line to ignore bower_components 199 | # (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) 200 | #bower_components/ 201 | 202 | # RIA/Silverlight projects 203 | Generated_Code/ 204 | 205 | # Backup & report files from converting an old project file 206 | # to a newer Visual Studio version. Backup files are not needed, 207 | # because we have git ;-) 208 | _UpgradeReport_Files/ 209 | Backup*/ 210 | UpgradeLog*.XML 211 | UpgradeLog*.htm 212 | 213 | # SQL Server files 214 | *.mdf 215 | *.ldf 216 | 217 | # Business Intelligence projects 218 | *.rdl.data 219 | *.bim.layout 220 | *.bim_*.settings 221 | 222 | # Microsoft Fakes 223 | FakesAssemblies/ 224 | 225 | # GhostDoc plugin setting file 226 | *.GhostDoc.xml 227 | 228 | # Node.js Tools for Visual Studio 229 | .ntvs_analysis.dat 230 | 231 | # Visual Studio 6 build log 232 | *.plg 233 | 234 | # Visual Studio 6 workspace options file 235 | *.opt 236 | 237 | # Visual Studio LightSwitch build output 238 | **/*.HTMLClient/GeneratedArtifacts 239 | **/*.DesktopClient/GeneratedArtifacts 240 | **/*.DesktopClient/ModelManifest.xml 241 | **/*.Server/GeneratedArtifacts 242 | **/*.Server/ModelManifest.xml 243 | _Pvt_Extensions 244 | 245 | # Paket dependency manager 246 | .paket/paket.exe 247 | paket-files/ 248 | 249 | # FAKE - F# Make 250 | .fake/ 251 | 252 | # JetBrains Rider 253 | .idea/ 254 | *.sln.iml 255 | 256 | # CodeRush 257 | .cr/ 258 | 259 | # Python Tools for Visual Studio (PTVS) 260 | __pycache__/ 261 | *.pyc -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # nt-mapper 2 | PE mapper in c++17 3 | 4 | # Features 5 | + Relocate image 6 | + Fix import address table 7 | + Handle api-set 8 | + Export directory parsing (forwarded and normal) 9 | + Two execution modes: 'Thread creation' and 'Thread hijacking' 10 | 11 | # Thread Hijacker 12 | + Preserves all registers, volatile or not 13 | + Exception 1: SSE registers 14 | + Exception 2: AVX registers 15 | + Preserves all flags 16 | + Automatically frees hijack shellcode after execution 17 | + Arbitrary shadow-space for dllmain 18 | + Aligns stack in case of recusant code 19 | 20 | # To-do 21 | + Static TLS 22 | + TLS callbacks 23 | + Loader entry 24 | + C++ exceptions 25 | 26 | # Thanks 27 | + DarthTon 28 | + Daax 29 | + JustMagic 30 | -------------------------------------------------------------------------------- /mapper.sln: -------------------------------------------------------------------------------- 1 |  2 | Microsoft Visual Studio Solution File, Format Version 12.00 3 | # Visual Studio 15 4 | VisualStudioVersion = 15.0.26430.15 5 | MinimumVisualStudioVersion = 10.0.40219.1 6 | Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "mapper", "mapper\mapper.vcxproj", "{76B7A704-E978-43F0-B627-47093398EDB2}" 7 | EndProject 8 | Global 9 | GlobalSection(SolutionConfigurationPlatforms) = preSolution 10 | Debug|x64 = Debug|x64 11 | Debug|x86 = Debug|x86 12 | Release|x64 = Release|x64 13 | Release|x86 = Release|x86 14 | EndGlobalSection 15 | GlobalSection(ProjectConfigurationPlatforms) = postSolution 16 | {76B7A704-E978-43F0-B627-47093398EDB2}.Debug|x64.ActiveCfg = Debug|x64 17 | {76B7A704-E978-43F0-B627-47093398EDB2}.Debug|x64.Build.0 = Debug|x64 18 | {76B7A704-E978-43F0-B627-47093398EDB2}.Debug|x86.ActiveCfg = Debug|Win32 19 | {76B7A704-E978-43F0-B627-47093398EDB2}.Debug|x86.Build.0 = Debug|Win32 20 | {76B7A704-E978-43F0-B627-47093398EDB2}.Release|x64.ActiveCfg = Release|x64 21 | {76B7A704-E978-43F0-B627-47093398EDB2}.Release|x64.Build.0 = Release|x64 22 | {76B7A704-E978-43F0-B627-47093398EDB2}.Release|x86.ActiveCfg = Release|Win32 23 | {76B7A704-E978-43F0-B627-47093398EDB2}.Release|x86.Build.0 = Release|Win32 24 | EndGlobalSection 25 | GlobalSection(SolutionProperties) = preSolution 26 | HideSolutionNode = FALSE 27 | EndGlobalSection 28 | GlobalSection(ExtensibilityGlobals) = postSolution 29 | SolutionGuid = {779F6AAD-C5AF-4438-BE12-A31B97414442} 30 | EndGlobalSection 31 | EndGlobal 32 | -------------------------------------------------------------------------------- /mapper/api_set.cpp: -------------------------------------------------------------------------------- 1 | #include "api_set.hpp" 2 | #include "transformer.hpp" 3 | 4 | #include 5 | #include 6 | #include 7 | 8 | api_set::api_set() noexcept 9 | { 10 | const auto peb = reinterpret_cast(NtCurrentTeb()->ProcessEnvironmentBlock); 11 | 12 | auto api_set = *reinterpret_cast(peb + 0x68); 13 | 14 | for (std::size_t entry_index = 0; entry_index < api_set->count; ++entry_index) 15 | { 16 | auto descriptor = api_set->entry(entry_index); 17 | 18 | std::wstring dll_name(MAX_PATH, L'\00'); 19 | api_set->read_name(descriptor, dll_name.data()); 20 | 21 | transformer::string_to_lower(dll_name, static_cast(MAX_PATH)); 22 | //std::transform(dll_name, dll_name_end, dll_name, ::tolower); 23 | 24 | auto host_data = api_set->get_host(descriptor); 25 | 26 | std::vector hosts; 27 | for (std::uint32_t j = 0; j < host_data->count; j++) 28 | { 29 | auto host = host_data->entry(api_set, j); 30 | 31 | std::wstring host_name(reinterpret_cast(reinterpret_cast(api_set) + host->value_offset), 32 | host->value_length / sizeof(wchar_t)); 33 | 34 | if (!host_name.empty()) 35 | { 36 | //wprintf(L"%s - %s\n", dll_name.c_str(), host_name.c_str()); 37 | hosts.push_back(host_name); 38 | } 39 | } 40 | 41 | this->schema.emplace(dll_name, hosts); 42 | } 43 | } 44 | 45 | bool api_set::query(std::wstring& name) noexcept 46 | { 47 | // SEARCH FOR ANY ENTRIES OF OUR PROXY DLL 48 | auto iter = std::find_if(this->schema.begin(), this->schema.end(), [name](const map_api_schema::value_type& val) 49 | { 50 | return name.find(val.first.c_str()) != name.npos; 51 | }); 52 | 53 | if (iter == this->schema.end()) // FOUND 54 | return false; 55 | 56 | name = iter->second.front() != name ? iter->second.front() : iter->second.back(); 57 | return true; 58 | } 59 | -------------------------------------------------------------------------------- /mapper/api_set.hpp: -------------------------------------------------------------------------------- 1 | #pragma once 2 | #include 3 | #include 4 | 5 | struct API_SET_VALUE_ENTRY 6 | { 7 | ULONG flags; 8 | ULONG name_offset; 9 | ULONG name_length; 10 | ULONG value_offset; 11 | ULONG value_length; 12 | }; 13 | 14 | struct API_SET_VALUE_ARRAY 15 | { 16 | ULONG flags; 17 | ULONG name_offset; 18 | ULONG unknown; 19 | ULONG name_length; 20 | ULONG data_offset; 21 | ULONG count; 22 | 23 | inline API_SET_VALUE_ENTRY* entry(void* api_set, SIZE_T index) noexcept 24 | { 25 | return reinterpret_cast(reinterpret_cast(api_set) + data_offset + index * sizeof(API_SET_VALUE_ENTRY)); 26 | } 27 | }; 28 | 29 | struct API_SET_NAMESPACE_ENTRY 30 | { 31 | ULONG limit; 32 | ULONG size; 33 | }; 34 | 35 | struct API_SET_NAMESPACE_ARRAY 36 | { 37 | ULONG version; 38 | ULONG size; 39 | ULONG flags; 40 | ULONG count; 41 | ULONG start; 42 | ULONG end; 43 | ULONG unknown[2]; 44 | 45 | inline API_SET_NAMESPACE_ENTRY* entry(SIZE_T index) noexcept 46 | { 47 | return reinterpret_cast(reinterpret_cast(this) + end + index * sizeof(API_SET_NAMESPACE_ENTRY)); 48 | } 49 | 50 | inline API_SET_VALUE_ARRAY* get_host(API_SET_NAMESPACE_ENTRY* entry_pointer) noexcept 51 | { 52 | return reinterpret_cast(reinterpret_cast(this) + start + sizeof(API_SET_VALUE_ARRAY) * entry_pointer->size); 53 | } 54 | 55 | inline void read_name(API_SET_NAMESPACE_ENTRY* entry_pointer, wchar_t* output) noexcept 56 | { 57 | auto array_pointer = get_host(entry_pointer); 58 | memcpy(output, reinterpret_cast(this) + array_pointer->name_offset, array_pointer->name_length); 59 | } 60 | }; 61 | 62 | 63 | using map_api_schema = std::unordered_map>; 64 | class api_set 65 | { 66 | public: 67 | api_set() noexcept; 68 | bool query(std::wstring& name) noexcept; 69 | private: 70 | map_api_schema schema; 71 | }; -------------------------------------------------------------------------------- /mapper/binary_file.cpp: -------------------------------------------------------------------------------- 1 | #include "binary_file.hpp" 2 | #include "logger.hpp" 3 | 4 | #include 5 | #include 6 | 7 | binary_file::binary_file(std::string_view file_path) 8 | { 9 | // CREATE FILE STREAM TO SPECIFIED PATH 10 | std::ifstream stream(file_path.data(), std::ios::binary); 11 | 12 | // SKIP WHITESPACES 13 | stream.unsetf(std::ios::skipws); 14 | 15 | // FIND LENGTH 16 | stream.seekg(0, std::ios::end); // GO TO END OF STREAM 17 | const auto length = stream.tellg(); // STORE STREAM POSITION 18 | stream.seekg(0, std::ios::beg); // GO TO BEGINNING OF STREAM 19 | 20 | // FILE NOT FOUND 21 | if (length == -1) 22 | return; 23 | 24 | // CREATE BUFFER 25 | this->m_buffer = std::vector(length); 26 | 27 | // COPY BUFFER FROM STREAM TO VECTOR 28 | stream.read(reinterpret_cast(this->m_buffer.data()), length); 29 | } 30 | 31 | const std::vector& binary_file::buffer() const noexcept 32 | { 33 | return this->m_buffer; 34 | } 35 | -------------------------------------------------------------------------------- /mapper/binary_file.hpp: -------------------------------------------------------------------------------- 1 | #pragma once 2 | #include 3 | #include 4 | 5 | class binary_file 6 | { 7 | public: 8 | explicit binary_file(std::string_view file_path); 9 | 10 | const std::vector& buffer() const noexcept; 11 | private: 12 | std::vector m_buffer; 13 | }; -------------------------------------------------------------------------------- /mapper/cast.hpp: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | #include 4 | 5 | namespace cast 6 | { 7 | template 8 | std::uintptr_t* long_pointer(T val) noexcept 9 | { 10 | // C-CAST DUE TO UNCERTAIN USE-CASES 11 | // THIS IS UNDEFINED BEHAVIOUR AND 12 | // STUPID, BUT IT LOOKS REALLY GOOD 13 | // :) 14 | return (std::uintptr_t*)(val); 15 | } 16 | 17 | template 18 | std::uint32_t* int_pointer(T val) noexcept 19 | { 20 | // C-CAST DUE TO UNCERTAIN USE-CASES 21 | // THIS IS UNDEFINED BEHAVIOUR AND 22 | // STUPID, BUT IT LOOKS REALLY GOOD 23 | // :) 24 | return (std::uint32_t*)(val); 25 | } 26 | 27 | 28 | // THIS IS SUPER UNDEFINED BEHAVIOUR BUT EYE-CANDY 29 | // FOR CONVERTING VOID* TO INTEGERS THROUGH TRUNCATION 30 | template 31 | T pointer_convert(void* val) noexcept 32 | { 33 | return static_cast(reinterpret_cast(val)); 34 | } 35 | } -------------------------------------------------------------------------------- /mapper/dllmain_call_x64.asm: -------------------------------------------------------------------------------- 1 | sub RSP, 0x28 2 | movabs RCX, 0x0000000000000000 ; hModule 3 | mov RDX, 0x1 ; fdwReason 4 | xor R8, R8 ; lpvReserved 5 | movabs RAX, 0x0000000000000000 ; DllMain Address 6 | call RAX 7 | add RSP, 0x28 8 | ret -------------------------------------------------------------------------------- /mapper/dllmain_hijack_x64.asm: -------------------------------------------------------------------------------- 1 | pushf 2 | push rax 3 | push rbx 4 | push rcx 5 | push rdx 6 | push rbp 7 | push rsi 8 | push rdi 9 | push r8 10 | push r9 11 | push r10 12 | push r11 13 | push r12 14 | push r13 15 | push r14 16 | push r15 17 | sub rsp,0x100 18 | 19 | movabs rcx,0x0 20 | mov rdx,0x1 21 | xor r8,r8 22 | movabs rax,0x0 23 | call rax 24 | 25 | add rsp,0x100 26 | pop r15 27 | pop r14 28 | pop r13 29 | pop r12 30 | pop r11 31 | pop r10 32 | pop r9 33 | pop r8 34 | pop rdi 35 | pop rsi 36 | pop rbp 37 | pop rdx 38 | pop rcx 39 | pop rbx 40 | pop rax 41 | popf 42 | mov qword ptr [rip+1], 1 43 | ret 44 | nop 45 | nop 46 | nop 47 | nop 48 | nop 49 | nop 50 | nop 51 | nop -------------------------------------------------------------------------------- /mapper/executors.cpp: -------------------------------------------------------------------------------- 1 | #include "executors.hpp" 2 | #include "cast.hpp" 3 | #include "logger.hpp" 4 | #include "safe_memory.hpp" 5 | #include "shellcode.hpp" 6 | 7 | #include 8 | #include 9 | 10 | 11 | bool injection::executors::hijack::handle_dllmain(const map_ctx& ctx, native::process& process) const noexcept 12 | { 13 | // CREATE SHELLCODE FOR IMAGE 14 | const auto entrypoint_offset = ctx.pe().get_optional_header().AddressOfEntryPoint; 15 | auto shellcode = shellcode::hijack_dllmain(ctx.remote_image(), ctx.remote_image() + entrypoint_offset); 16 | 17 | // ALLOCATE AND INITIALISE MEMORY HANDLER (RAII) 18 | auto remote_buffer = safe_memory( 19 | &process, 20 | process.raw_allocate(shellcode.size())); 21 | 22 | logger::log_formatted("Shellcode", remote_buffer.memory(), true); 23 | 24 | // FAILED TO ALLOCATE? 25 | if (!remote_buffer) 26 | { 27 | logger::log_error("Failed to allocate shellcode"); 28 | return false; 29 | } 30 | 31 | // FAILED TO WRITE? 32 | if (!process.write_raw_memory(shellcode.data(), remote_buffer.memory(), shellcode.size())) 33 | { 34 | logger::log_error("Failed to write shellcode"); 35 | return false; 36 | } 37 | 38 | for (auto& thread : process.threads()) 39 | { 40 | // FIND A THREAD THAT IS IDLE 41 | const auto is_waiting = thread.state() == native::thread::state_t::WAITING; 42 | 43 | const auto is_user_requested_delay = 44 | thread.wait_reason() == native::thread::wait_reason_t::USER_REQUEST || thread.wait_reason() == native::thread::wait_reason_t::WR_USER_REQUEST; 45 | 46 | if (!is_waiting || !is_user_requested_delay) 47 | continue; 48 | 49 | logger::log_formatted("Hijackable Thread", thread.thread_id(), false); 50 | 51 | // SUSPEND THREAD TO MODIFY IT'S CONTEXT 52 | if (!thread.suspend()) 53 | { 54 | logger::log_error("Failed to suspend hijackable thread."); 55 | return false; 56 | } 57 | 58 | // ALLOCATE AND WRITE A OLD INSTRUCTION POINTER ON STACK 59 | thread.context().Rsp -= sizeof(std::uintptr_t); 60 | 61 | // ALIGN STACK TO DEFAULT 8-BYTE ALIGNMENT ? 62 | // thread.context().Rsp &= 0xFFFFFFFFFFFFFFF8; 63 | 64 | if (!process.write_memory(thread.context().Rip, thread.context().Rsp)) 65 | { 66 | logger::log_error("Failed to write instruction pointer to stack."); 67 | return false; 68 | } 69 | 70 | // SET NEW INSTRUCTION POINTER 71 | thread.context().Rip = remote_buffer.memory(); 72 | 73 | logger::log_formatted("New Stack pointer", thread.context().Rsp, true); 74 | logger::log_formatted("Instruction pointer", thread.context().Rip, true); 75 | logger::log_formatted("Entrypoint", ctx.remote_image() + entrypoint_offset, true); 76 | 77 | // RESUME THREAD TO RUN OUR SHELLCODE 78 | if (!thread.resume()) 79 | { 80 | logger::log_error("Failed to resume hijackable thread."); 81 | return false; 82 | } 83 | 84 | // WAIT FOR THREAD TO FINISH 85 | // ... 86 | // AT THE END OF THE SHELLCODE, IT WRITES 0x1 TO SHELLCODE+6a TO ALERT EXECUTOR 87 | // OF IT'S SUCCESS :) 88 | const auto marker_address = remote_buffer.memory() + shellcode.size() - 8; 89 | for (std::uint8_t marker = 0x00; marker != 0x01; process.read_memory(&marker, marker_address)) 90 | { 91 | std::this_thread::sleep_for(std::chrono::milliseconds(1)); 92 | } 93 | 94 | return true; 95 | } 96 | 97 | return false; 98 | } 99 | 100 | bool injection::executors::create::handle_dllmain(const map_ctx& ctx, native::process& process) const noexcept 101 | { 102 | // CREATE SHELLCODE FOR IMAGE 103 | const auto entrypoint_offset = ctx.pe().get_optional_header().AddressOfEntryPoint; 104 | auto shellcode = shellcode::call_dllmain(ctx.remote_image(), ctx.remote_image() + entrypoint_offset); 105 | 106 | // ALLOCATE AND INITIALISE MEMORY HANDLER (RAII) 107 | auto remote_buffer = safe_memory( 108 | &process, 109 | process.raw_allocate(shellcode.size())); 110 | 111 | // FAILED TO ALLOCATE? 112 | if (!remote_buffer) 113 | { 114 | logger::log_error("Failed to allocate shellcode"); 115 | return false; 116 | } 117 | 118 | // FAILED TO WRITE? 119 | if (!process.write_raw_memory(shellcode.data(), remote_buffer.memory(), shellcode.size())) 120 | { 121 | logger::log_error("Failed to write shellcode"); 122 | return false; 123 | } 124 | 125 | // FAILED TO CREATE THREAD? 126 | auto thread = process.create_thread(remote_buffer.memory(), 0x00); 127 | if (!thread) 128 | { 129 | logger::log_error("Failed to create shellcode thread"); 130 | return false; 131 | } 132 | 133 | // FAILED TO WAIT FOR THREAD? 134 | if (!thread.wait()) 135 | { 136 | logger::log_error("Failed to wait for shellcode thread"); 137 | return false; 138 | } 139 | 140 | // SUCCESSFULLY RAN SHELLCODE, MEMORY GET'S FREED BY HANDLER 141 | // WHEN IT GOES OUT OF SCOPE 142 | return true; 143 | } 144 | -------------------------------------------------------------------------------- /mapper/executors.hpp: -------------------------------------------------------------------------------- 1 | #pragma once 2 | #include "map_context.hpp" 3 | #include "process.hpp" 4 | 5 | 6 | namespace injection::executors 7 | { 8 | class hijack 9 | { 10 | public: 11 | bool handle_dllmain(const map_ctx& ctx, native::process& process) const noexcept; 12 | }; 13 | 14 | class create 15 | { 16 | public: 17 | bool handle_dllmain(const map_ctx& ctx, native::process& process) const noexcept; 18 | }; 19 | 20 | } -------------------------------------------------------------------------------- /mapper/loadlibrary.cpp: -------------------------------------------------------------------------------- 1 | #include "loadlibrary.hpp" 2 | #include "process.hpp" 3 | #include "logger.hpp" 4 | #include "safe_memory.hpp" 5 | 6 | 7 | bool injection::loadlibrary::inject(std::string_view buffer) noexcept 8 | { 9 | // ALLOCATE AND INITIALISE MEMORY HANDLER (RAII) 10 | auto remote_buffer = safe_memory( 11 | &process, 12 | process.raw_allocate(buffer.size())); 13 | 14 | // FAILED TO ALLOCATE? 15 | if (!remote_buffer) 16 | { 17 | logger::log_error("Failed to allocate path"); 18 | return false; 19 | } 20 | 21 | // FAILED TO WRITE? 22 | if (!process.write_raw_memory(buffer.data(), remote_buffer.memory(), buffer.length())) 23 | { 24 | logger::log_error("Failed to write path"); 25 | return false; 26 | } 27 | 28 | // FIND LOADLIBRARY 29 | const auto module_handle = GetModuleHandle(L"kernel32.dll"); 30 | const auto function_pointer = reinterpret_cast(GetProcAddress(module_handle, "LoadLibraryA")); 31 | 32 | // FAILED TO CREATE THREAD? 33 | auto thread = process.create_thread(function_pointer, remote_buffer.memory()); 34 | if (!thread) 35 | { 36 | logger::log_error("Failed to create loadlibrary thread"); 37 | return false; 38 | } 39 | 40 | // FAILED TO WAIT FOR THREAD? 41 | if (!thread.wait()) 42 | { 43 | logger::log_error("Failed to wait for loadlibrary thread"); 44 | return false; 45 | } 46 | 47 | return true; 48 | } 49 | -------------------------------------------------------------------------------- /mapper/loadlibrary.hpp: -------------------------------------------------------------------------------- 1 | #pragma once 2 | #include "process.hpp" 3 | #include 4 | 5 | namespace injection 6 | { 7 | class loadlibrary 8 | { 9 | public: 10 | explicit loadlibrary(native::process& proc) noexcept : process(proc) {} 11 | bool inject(std::string_view buffer) noexcept; 12 | 13 | protected: 14 | native::process& process; 15 | }; 16 | } 17 | -------------------------------------------------------------------------------- /mapper/logger.cpp: -------------------------------------------------------------------------------- 1 | #include "logger.hpp" 2 | 3 | void logger::log(std::string_view message) noexcept 4 | { 5 | std::cout << "[+] " << message << std::endl; 6 | } 7 | 8 | void logger::log_error(std::string_view message) noexcept 9 | { 10 | std::cout << "[!] " << message << std::endl; 11 | } 12 | -------------------------------------------------------------------------------- /mapper/logger.hpp: -------------------------------------------------------------------------------- 1 | #pragma once 2 | #include 3 | #include 4 | 5 | namespace logger 6 | { 7 | void log(std::string_view message) noexcept; 8 | void log_error(std::string_view message) noexcept; 9 | 10 | template 11 | void log_formatted(std::string_view variable_name, const T& variable_data, const bool hexadecimal) noexcept 12 | { 13 | std::cout << "[?] " << variable_name << ": "; 14 | std::cout << (hexadecimal ? std::hex : std::dec); 15 | std::cout << variable_data << std::dec; 16 | std::cout << std::endl; 17 | } 18 | } -------------------------------------------------------------------------------- /mapper/main.cpp: -------------------------------------------------------------------------------- 1 | #define NOMINMAX 2 | 3 | #include "ntdll.hpp" 4 | #include "process.hpp" 5 | #include "manualmapper.hpp" 6 | #include "logger.hpp" 7 | #include "binary_file.hpp" 8 | #include "executors.hpp" 9 | 10 | #include 11 | #include 12 | 13 | int main() 14 | { 15 | // INTIALISE NATIVE FUNCTIONS 16 | ntdll::initialise(); 17 | 18 | //logger::log("Process name:"); 19 | //std::string process_name{}; 20 | //std::cin >> process_name; 21 | 22 | const auto process_name = std::string("notepad.exe"); 23 | 24 | // FIND PROCESS 25 | auto proc = native::process(process_name.c_str(), PROCESS_ALL_ACCESS); 26 | logger::log_formatted("Target process id", proc.get_id(), false); 27 | 28 | // READ BUFFER 29 | binary_file image("C:\\Users\\Admin\\Google Drive\\TestPEs\\DLLTEST64.dll"); 30 | 31 | if (image.buffer().size() == 0x00) 32 | { 33 | logger::log_error("Failed to find binary file!"); 34 | return 0; 35 | } 36 | 37 | // CREATE MAPPER INSTANCE 38 | auto mapper = injection::manualmapper(proc); 39 | 40 | // INJECT IMAGE INTO PROCESS 41 | const auto injected_ctx = mapper.inject(image.buffer()); 42 | logger::log_formatted("Injected buffer", injected_ctx.remote_image(), true); 43 | 44 | // PATCH TERMINATEPROCESS 45 | // proc.write_memory(0xC3, reinterpret_cast(TerminateProcess)); 46 | 47 | // CALL IT USING SPECIFIED EXECUTOR 48 | const auto executed = mapper.call(injected_ctx, injection::executors::create{}); 49 | 50 | logger::log_formatted("Executed", executed, true); 51 | 52 | std::cin.clear(); 53 | std::cin.ignore(std::numeric_limits::max(), '\n'); 54 | std::cin.get(); 55 | 56 | return 0; 57 | } 58 | 59 | -------------------------------------------------------------------------------- /mapper/maker.hpp: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | #include 4 | #include 5 | 6 | namespace maker 7 | { 8 | template 9 | __forceinline std::array create_byte_array(T&&... bytes) noexcept { 10 | return { std::byte(bytes)... }; 11 | } 12 | } -------------------------------------------------------------------------------- /mapper/manualmapper.cpp: -------------------------------------------------------------------------------- 1 | #include "manualmapper.hpp" 2 | #include "logger.hpp" 3 | #include "binary_file.hpp" 4 | #include "cast.hpp" 5 | 6 | #include 7 | #include 8 | 9 | map_ctx injection::manualmapper::inject(const std::vector& buffer) noexcept 10 | { 11 | // GET LINKED MODULES FOR LATER USE 12 | this->linked_modules() = this->process().get_modules(); 13 | 14 | // INITIALISE CONTEXT 15 | map_ctx ctx("Main Image", buffer); 16 | 17 | // MAP MAIN IMAGE AND ALL DEPENDENCIES 18 | return map_image(ctx) ? ctx : map_ctx{}; 19 | } 20 | 21 | bool injection::manualmapper::map_image(map_ctx& ctx) noexcept 22 | { 23 | // CREATE A MEMORY SECTION THAT CAN BE MAPPED INTO SEPERATE PROCESSES 24 | // AND REFLECT EACH OTHER, ALLOWING FOR EASY MEMORY ACCESS 25 | auto section = memory_section(PAGE_EXECUTE_READWRITE, ctx.pe().get_optional_header().SizeOfImage); 26 | if (!section) 27 | { 28 | logger::log_error("Failed to create section"); 29 | return false; 30 | } 31 | 32 | // MAP SECTION INTO BOTH LOCAL AND REMOTE PROCESS 33 | ctx.set_local_image(native::process::current_process().map(section)); 34 | ctx.set_remote_image(this->process().map(section)); 35 | 36 | if (!ctx.local_image() || !ctx.remote_image()) 37 | { 38 | logger::log_error("Failed to map section"); 39 | return false; 40 | } 41 | 42 | // ADD MAPPED MODULE TO LIST OF MODULES 43 | this->mapped_modules().emplace_back(ctx); 44 | 45 | logger::log_formatted("Mapping image", ctx.image_name(), false); 46 | 47 | // MANUALMAP IMAGE 48 | write_headers(ctx); // WRITE PORTABLE EXECUTABLE HEADERS, THESE CONTAIN METADATA OF THE IMAGE 49 | write_image_sections(ctx); // WRITE IMAGE SECTIONS, THESE CONTAIN THE ACTUAL DATA THAT IS THE IMAGE 50 | fix_import_table(ctx); // FIX IMPORTED FUNCTIONS IN THE IMPORT TABLE 51 | relocate_image_by_delta(ctx); // RELOCATE IMAGE BY PARSING RELOCATION DATA AND HANDLING POINTERS FOR THE NEW IMAGE BASE 52 | 53 | // TODO: 54 | // HANDLE TLS CALLBACKS 55 | // HANDLE STATIC TLS DATA 56 | // HANDLE C++ EXCEPTIONS 57 | // INSERT LOADER ENTRIES (DOCUMENTED AND UNDOCUMENTED) 58 | 59 | return true; 60 | } 61 | 62 | uintptr_t injection::manualmapper::find_or_map_dependency(const std::string& image_name) noexcept 63 | { 64 | // HAVE WE MAPPED THIS DEPENDENCY ALREADY? 65 | for (auto& module : this->mapped_modules()) 66 | { 67 | if (module.image_name() == image_name) 68 | return module.remote_image(); 69 | } 70 | 71 | // WAS THIS DEPENDENCY ALREADY LOADED BY LDR? 72 | if (auto iterator = this->linked_modules().find(image_name); iterator != this->linked_modules().end()) 73 | return iterator->second; 74 | 75 | logger::log_formatted("Failed to find loaded dependency", image_name, false); 76 | 77 | // TODO: PROPER FILE SEARCHING? 78 | binary_file file("C:\\Windows\\System32\\" + image_name); 79 | auto ctx = map_ctx(image_name, file.buffer()); 80 | 81 | // MAP DEPENDENCY 82 | return map_image(ctx) ? ctx.remote_image() : 0x00; 83 | } 84 | 85 | void injection::manualmapper::write_headers(map_ctx& ctx) noexcept 86 | { 87 | // COPY OVER PE HEADERS TO MAPPED SECTION 88 | std::memcpy( 89 | reinterpret_cast(ctx.local_image()), // DESTINATION 90 | ctx.pe_buffer(), // SOURCE 91 | ctx.pe().get_optional_header().SizeOfHeaders); // SIZE 92 | } 93 | 94 | void injection::manualmapper::write_image_sections(map_ctx& ctx) noexcept 95 | { 96 | // APPLY READ-ONLY PROTECTION TO PE-HEADERS 97 | //std::uint32_t old_protection; 98 | //this->process().virtual_protect(ctx.remote_image(), PAGE_READONLY, &old_protection, 0x1000); 99 | 100 | // COPY EACH PE SECTION TO MAPPED SECTION 101 | for (const auto& section : ctx.pe().get_sections()) 102 | { 103 | // COPY RAW DATA OF SECTION 104 | std::memcpy( 105 | reinterpret_cast(ctx.local_image() + section.virtual_address()), // DESTINATION 106 | ctx.pe_buffer() + section.raw_data_offset(), // SOURCE 107 | section.raw_size()); // SIZE 108 | 109 | // PARSE PROTECTION FROM CHARACTERISTICS 110 | std::uint32_t virtual_protection = 0x00; 111 | 112 | // NO ACCESSS 113 | if (!section.is_readable()) 114 | { 115 | virtual_protection = PAGE_NOACCESS; 116 | } 117 | 118 | // WRITABLE 119 | if (section.is_writable()) 120 | { 121 | virtual_protection = section.is_executable() ? PAGE_EXECUTE_READWRITE : PAGE_READWRITE; 122 | } 123 | else 124 | { 125 | virtual_protection = section.is_executable() ? PAGE_EXECUTE_READ : PAGE_READONLY; 126 | } 127 | 128 | // APPLY VIRTUAL FLAGS TO REMOTE PROCESS 129 | //auto result = this->process().virtual_protect( 130 | // ctx.remote_image() + section.virtual_address(), 131 | // virtual_protection, &old_protection, 132 | // section.virtual_size()); 133 | 134 | //if (!result) 135 | //{ 136 | // logger::log_error("Failed to protect section"); 137 | // logger::log_formatted("Last error", GetLastError(), true); 138 | // logger::log_formatted("Section name", section.raw_header().Name, false); 139 | // logger::log_formatted("Protection", virtual_protection, true); 140 | // 141 | // logger::log("Arguments:"); 142 | // logger::log_formatted("1", ctx.remote_image() + section.virtual_address(), true); 143 | // logger::log_formatted("2", virtual_protection, true); 144 | // logger::log_formatted("3", &old_protection, true); 145 | // logger::log_formatted("4", section.raw_size(), true); 146 | //} 147 | } 148 | } 149 | 150 | void injection::manualmapper::relocate_image_by_delta(map_ctx& ctx) noexcept 151 | { 152 | // CHANGE IN BASE ADDRESS (DEFAULT -> MAPPED) 153 | const auto delta = ctx.remote_image() - ctx.pe().get_image_base(); 154 | 155 | // UPDATE POINTERS WITH THE NEW IMAGE BASE DIFFERENCE 156 | for (auto&[entry, item] : ctx.pe().get_relocations(ctx.local_image())) 157 | *cast::long_pointer(ctx.local_image() + entry.page_rva + item.get_offset()) += delta; 158 | } 159 | 160 | void injection::manualmapper::fix_import_table(map_ctx& ctx) noexcept 161 | { 162 | wstring_converter_t converter; 163 | api_set api_schema; 164 | 165 | for (const auto&[map_key, functions] : ctx.pe().get_imports(ctx.local_image())) 166 | { 167 | auto module_name = map_key; 168 | 169 | // QUERY API SCHEMA FOR NAME 170 | std::wstring wide_module_name = converter.from_bytes(module_name.c_str()); 171 | if (api_schema.query(wide_module_name)) 172 | module_name = converter.to_bytes(wide_module_name); 173 | 174 | const auto module_handle = find_or_map_dependency(module_name); 175 | if (!module_handle) 176 | { 177 | logger::log_error("Failed to map dependency"); 178 | return; 179 | } 180 | 181 | // ITERATE IMPORTED FUNCTIONS 182 | for (const auto& fn : functions) 183 | { 184 | // GET THE FUNCTION EXPORT 185 | const auto function_ordinal = fn.ordinal > 0 ? reinterpret_cast(fn.ordinal) : fn.name.c_str(); 186 | auto exported_function = this->process().get_module_export(module_handle, function_ordinal); 187 | 188 | // HANDLE FORWARDED EXPORTS RECURSIVELY 189 | while (exported_function.forwarded) 190 | { 191 | exported_function = handle_forwarded_export(exported_function, api_schema); 192 | } 193 | 194 | // UPDATE IMPORTED FUNCTION POINTER 195 | if (exported_function.function != 0x00) 196 | { 197 | *cast::long_pointer(ctx.local_image() + fn.function_rva) = exported_function.function; 198 | } 199 | else 200 | { 201 | logger::log_error("Failed to handle imported function."); 202 | logger::log_formatted("Function name", function_ordinal, false); 203 | } 204 | } 205 | } 206 | } 207 | 208 | native::process::module_export injection::manualmapper::handle_forwarded_export(native::process::module_export& exported_function, api_set& api_schema) noexcept 209 | { 210 | // QUERY API SCHEMA FOR NAME 211 | wstring_converter_t converter; 212 | auto library_name = exported_function.forwarded_library; 213 | std::wstring wide_forwarded_library_name = converter.from_bytes(library_name.c_str()); 214 | if (api_schema.query(wide_forwarded_library_name)) 215 | library_name = converter.to_bytes(wide_forwarded_library_name); 216 | 217 | logger::log_formatted("Library name", library_name, false); 218 | logger::log_formatted("Function name", exported_function.forwarded_name, false); 219 | 220 | // TODO: PROPER FILE SEARCHING? 221 | binary_file file("C:\\Windows\\System32\\" + library_name); 222 | auto forwarded_ctx = map_ctx(library_name, file.buffer()); 223 | 224 | // MAP FORWARDED LIBRARY 225 | if (map_image(forwarded_ctx)) 226 | { 227 | logger::log_error("Failed to map forwarded library."); 228 | return native::process::module_export(0x00); 229 | } 230 | 231 | // FIND FORWARDED EXPORT 232 | return this->process().get_module_export(forwarded_ctx.remote_image(), exported_function.forwarded_name.c_str()); 233 | } 234 | 235 | native::process::module_list_t& injection::manualmapper::linked_modules() noexcept 236 | { 237 | return this->m_linked_modules; 238 | } 239 | 240 | std::vector& injection::manualmapper::mapped_modules() noexcept 241 | { 242 | return this->m_mapped_modules; 243 | } 244 | 245 | native::process& injection::manualmapper::process() noexcept 246 | { 247 | return this->m_process; 248 | } -------------------------------------------------------------------------------- /mapper/manualmapper.hpp: -------------------------------------------------------------------------------- 1 | #pragma once 2 | #include "process.hpp" 3 | #include "portable_executable.hpp" 4 | #include "map_context.hpp" 5 | #include "api_set.hpp" 6 | 7 | #include 8 | #include 9 | #include 10 | 11 | namespace injection 12 | { 13 | class manualmapper 14 | { 15 | public: 16 | explicit manualmapper(native::process& proc) noexcept : m_process(proc) { } 17 | 18 | // INJECT IMAGE INTO PROCESS 19 | map_ctx inject(const std::vector& buffer) noexcept; 20 | 21 | template 22 | bool call(const map_ctx& ctx, const Executor&& executor) noexcept 23 | { 24 | // EXECUTE THE IMAGE, HANDLED BY EXECUTION ENGINE 25 | return executor.handle_dllmain(ctx, this->process()); 26 | } 27 | 28 | private: 29 | void write_headers(map_ctx& ctx) noexcept; 30 | bool map_image(map_ctx& ctx) noexcept; 31 | std::uintptr_t find_or_map_dependency(const std::string& image_name) noexcept; 32 | void write_image_sections(map_ctx& ctx) noexcept; 33 | void relocate_image_by_delta(map_ctx& ctx) noexcept; 34 | void fix_import_table(map_ctx& ctx) noexcept; 35 | native::process::module_export handle_forwarded_export(native::process::module_export& exported_function, api_set& api_schema) noexcept; 36 | 37 | native::process::module_list_t& linked_modules() noexcept; 38 | std::vector& mapped_modules() noexcept; 39 | native::process& process() noexcept; 40 | 41 | native::process::module_list_t m_linked_modules; 42 | std::vector m_mapped_modules; 43 | native::process& m_process; 44 | }; 45 | } -------------------------------------------------------------------------------- /mapper/map_context.cpp: -------------------------------------------------------------------------------- 1 | #include "map_context.hpp" 2 | 3 | const std::byte* map_ctx::pe_buffer() const noexcept 4 | { 5 | return this->pe().get_buffer().data(); 6 | } 7 | 8 | const portable_executable& map_ctx::pe() const noexcept 9 | { 10 | return this->m_pe; 11 | } 12 | 13 | const std::string& map_ctx::image_name() const noexcept 14 | { 15 | return this->m_image_name; 16 | } 17 | 18 | std::uintptr_t map_ctx::local_image() const noexcept 19 | { 20 | return this->m_local_image; 21 | } 22 | 23 | std::uintptr_t map_ctx::remote_image() const noexcept 24 | { 25 | return this->m_remote_image; 26 | } 27 | 28 | void map_ctx::set_local_image(std::uintptr_t image) 29 | { 30 | this->m_local_image = image; 31 | } 32 | 33 | void map_ctx::set_remote_image(std::uintptr_t image) 34 | { 35 | this->m_remote_image = image; 36 | } 37 | -------------------------------------------------------------------------------- /mapper/map_context.hpp: -------------------------------------------------------------------------------- 1 | #pragma once 2 | #include 3 | #include 4 | 5 | #include "portable_executable.hpp" 6 | 7 | class map_ctx 8 | { 9 | public: 10 | map_ctx() noexcept {} 11 | explicit map_ctx(std::string_view new_image_name, const std::vector& new_buffer) noexcept : 12 | m_image_name(new_image_name), m_pe(new_buffer) {} 13 | 14 | const std::byte* pe_buffer() const noexcept; 15 | const portable_executable& pe() const noexcept; 16 | const std::string& image_name() const noexcept; 17 | std::uintptr_t local_image() const noexcept; 18 | std::uintptr_t remote_image() const noexcept; 19 | 20 | void set_local_image(std::uintptr_t image); 21 | void set_remote_image(std::uintptr_t image); 22 | 23 | private: 24 | const std::string m_image_name; 25 | portable_executable m_pe; 26 | std::uintptr_t m_local_image; 27 | std::uintptr_t m_remote_image; 28 | }; 29 | -------------------------------------------------------------------------------- /mapper/mapper.vcxproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 5 | Debug 6 | Win32 7 | 8 | 9 | Release 10 | Win32 11 | 12 | 13 | Debug 14 | x64 15 | 16 | 17 | Release 18 | x64 19 | 20 | 21 | 22 | 15.0 23 | {76B7A704-E978-43F0-B627-47093398EDB2} 24 | Win32Proj 25 | mapper 26 | 10.0.17134.0 27 | 28 | 29 | 30 | Application 31 | true 32 | v141 33 | Unicode 34 | 35 | 36 | Application 37 | false 38 | v141 39 | true 40 | Unicode 41 | 42 | 43 | Application 44 | true 45 | v141 46 | Unicode 47 | 48 | 49 | Application 50 | false 51 | v141 52 | true 53 | Unicode 54 | 55 | 56 | 57 | 58 | 59 | 60 | 61 | 62 | 63 | 64 | 65 | 66 | 67 | 68 | 69 | 70 | 71 | 72 | 73 | 74 | true 75 | 76 | 77 | true 78 | 79 | 80 | false 81 | 82 | 83 | false 84 | 85 | 86 | 87 | Use 88 | Level3 89 | Disabled 90 | WIN32;_DEBUG;_CONSOLE;%(PreprocessorDefinitions) 91 | 92 | 93 | Console 94 | 95 | 96 | 97 | 98 | NotUsing 99 | Level3 100 | Disabled 101 | _DEBUG;_CONSOLE;%(PreprocessorDefinitions) 102 | stdcpplatest 103 | 104 | 105 | Console 106 | 107 | 108 | 109 | 110 | Level3 111 | Use 112 | MaxSpeed 113 | true 114 | true 115 | WIN32;NDEBUG;_CONSOLE;%(PreprocessorDefinitions) 116 | 117 | 118 | Console 119 | true 120 | true 121 | 122 | 123 | 124 | 125 | Level4 126 | NotUsing 127 | MaxSpeed 128 | true 129 | true 130 | NDEBUG;_CONSOLE;%(PreprocessorDefinitions) 131 | stdcpplatest 132 | true 133 | 134 | 135 | Console 136 | true 137 | true 138 | ntdll.lib;%(AdditionalDependencies) 139 | 140 | 141 | 142 | 143 | 144 | 145 | 146 | 147 | 148 | 149 | 150 | 151 | 152 | 153 | 154 | 155 | 156 | 157 | 158 | 159 | 160 | 161 | 162 | 163 | 164 | 165 | 166 | 167 | 168 | 169 | 170 | 171 | 172 | 173 | 174 | 175 | 176 | 177 | 178 | 179 | 180 | 181 | 182 | 183 | 184 | -------------------------------------------------------------------------------- /mapper/mapper.vcxproj.filters: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 5 | {4FC737F1-C7A5-4376-A066-2A32D752A2FF} 6 | cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx 7 | 8 | 9 | {93995380-89BD-4b04-88EB-625FBE52EBFB} 10 | h;hh;hpp;hxx;hm;inl;inc;xsd 11 | 12 | 13 | {67DA6AB6-F800-4c08-8B7A-83BB121AAD01} 14 | rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav;mfcribbon-ms 15 | 16 | 17 | {5488219a-4366-4b02-9c48-35703f2ccfc5} 18 | 19 | 20 | {36ed4480-f964-4653-a204-2d64590f897b} 21 | 22 | 23 | {f4ca6086-be0a-474b-af13-fa26c2cbc5f8} 24 | 25 | 26 | {4aa3c00e-ce7c-49fc-b527-74b03e3213c7} 27 | 28 | 29 | {ba977a78-646a-4bca-a4a2-edb4e487c0bb} 30 | 31 | 32 | {80a5c3ad-968a-4413-b048-de81532aa277} 33 | 34 | 35 | {19ceadce-4d10-469a-9a43-dc8e6e640168} 36 | 37 | 38 | {7204e0d4-6941-4342-b130-5b7c905b2254} 39 | 40 | 41 | {352ecd43-9a8e-4ec4-9998-d2ae56da30c6} 42 | 43 | 44 | {610f320f-6071-421f-886b-1b5eec5d6fbc} 45 | 46 | 47 | {74235fac-b308-4444-bef4-05013be59c0a} 48 | 49 | 50 | 51 | 52 | Header Files\Injection 53 | 54 | 55 | Header Files\Helpers 56 | 57 | 58 | Header Files\Helpers 59 | 60 | 61 | Header Files\Interop 62 | 63 | 64 | Header Files\Wrapper 65 | 66 | 67 | Header Files\Helpers 68 | 69 | 70 | Header Files\Helpers 71 | 72 | 73 | Header Files\Injection 74 | 75 | 76 | Header Files\Injection 77 | 78 | 79 | Header Files\Interop 80 | 81 | 82 | Header Files\Interop 83 | 84 | 85 | Header Files\Wrapper 86 | 87 | 88 | Header Files\Wrapper 89 | 90 | 91 | Header Files\Interop 92 | 93 | 94 | Header Files\Engines 95 | 96 | 97 | Header Files\Helpers 98 | 99 | 100 | Header Files\Interop 101 | 102 | 103 | Header Files\Engines 104 | 105 | 106 | Header Files\Interop 107 | 108 | 109 | 110 | 111 | Source Files 112 | 113 | 114 | Source Files\Injection 115 | 116 | 117 | Source Files\Helpers 118 | 119 | 120 | Source Files\Interop 121 | 122 | 123 | Source Files\Wrapper 124 | 125 | 126 | Source Files\Injection 127 | 128 | 129 | Source Files\Injection 130 | 131 | 132 | Source Files\Wrapper 133 | 134 | 135 | Source Files\Wrapper 136 | 137 | 138 | Source Files\Helpers 139 | 140 | 141 | Source Files\Interop 142 | 143 | 144 | Source Files\Engines 145 | 146 | 147 | Source Files\Engines 148 | 149 | 150 | 151 | 152 | Shellcodes 153 | 154 | 155 | Shellcodes 156 | 157 | 158 | -------------------------------------------------------------------------------- /mapper/mapper.vcxproj[Conflict].filters: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 5 | {4FC737F1-C7A5-4376-A066-2A32D752A2FF} 6 | cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx 7 | 8 | 9 | {93995380-89BD-4b04-88EB-625FBE52EBFB} 10 | h;hh;hpp;hxx;hm;inl;inc;xsd 11 | 12 | 13 | {67DA6AB6-F800-4c08-8B7A-83BB121AAD01} 14 | rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav;mfcribbon-ms 15 | 16 | 17 | {5488219a-4366-4b02-9c48-35703f2ccfc5} 18 | 19 | 20 | {36ed4480-f964-4653-a204-2d64590f897b} 21 | 22 | 23 | {f4ca6086-be0a-474b-af13-fa26c2cbc5f8} 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | Header Files 32 | 33 | 34 | Header Files 35 | 36 | 37 | Header Files\Injection 38 | 39 | 40 | Header Files\Injection 41 | 42 | 43 | Header Files 44 | 45 | 46 | Header Files 47 | 48 | 49 | Header Files 50 | 51 | 52 | Header Files\Helpers 53 | 54 | 55 | 56 | 57 | Source Files 58 | 59 | 60 | Source Files 61 | 62 | 63 | Source Files\Injection 64 | 65 | 66 | Source Files 67 | 68 | 69 | Source Files 70 | 71 | 72 | Source Files 73 | 74 | 75 | Source Files\Injection 76 | 77 | 78 | -------------------------------------------------------------------------------- /mapper/memory_section.hpp: -------------------------------------------------------------------------------- 1 | #pragma once 2 | #include "safe_handle.hpp" 3 | #include "ntdll.hpp" 4 | #include "logger.hpp" 5 | 6 | #include 7 | 8 | class memory_section 9 | { 10 | public: 11 | explicit memory_section(std::uint32_t page_protection, std::uint64_t size) noexcept 12 | { 13 | LARGE_INTEGER large_size{}; 14 | large_size.QuadPart = size; 15 | 16 | HANDLE new_handle; 17 | auto result = ntdll::NtCreateSection(&new_handle, GENERIC_ALL, 0, &large_size, page_protection, SEC_COMMIT, 0); 18 | 19 | if (!NT_SUCCESS(result)) 20 | { 21 | logger::log_error("NtCreateSection failed"); 22 | return; 23 | } 24 | 25 | this->m_handle = safe_handle(new_handle); 26 | this->m_protection = page_protection; 27 | this->m_size = size; 28 | } 29 | 30 | explicit operator bool() const noexcept 31 | { 32 | return static_cast(this->m_handle); 33 | } 34 | 35 | inline auto handle() const noexcept -> const safe_handle& 36 | { 37 | return this->m_handle; 38 | } 39 | 40 | inline auto protection() const noexcept -> std::uint32_t 41 | { 42 | return this->m_protection; 43 | } 44 | 45 | inline auto size() const noexcept -> std::uint64_t 46 | { 47 | return this->m_size; 48 | } 49 | 50 | private: 51 | safe_handle m_handle; 52 | std::uint32_t m_protection; 53 | std::uint64_t m_size; 54 | }; -------------------------------------------------------------------------------- /mapper/ntdll.cpp: -------------------------------------------------------------------------------- 1 | #include "ntdll.hpp" 2 | 3 | NtCreateSection_t ntdll::NtCreateSection = nullptr; 4 | NtMapViewOfSection_t ntdll::NtMapViewOfSection = nullptr; 5 | NtQuerySystemInformation_t ntdll::NtQuerySystemInformation = nullptr; 6 | 7 | void ntdll::initialise() noexcept 8 | { 9 | const auto module_handle = GetModuleHandle(L"ntdll.dll"); 10 | ntdll::NtCreateSection = reinterpret_cast(GetProcAddress(module_handle, "NtCreateSection")); 11 | ntdll::NtMapViewOfSection = reinterpret_cast(GetProcAddress(module_handle, "NtMapViewOfSection")); 12 | ntdll::NtQuerySystemInformation = reinterpret_cast(GetProcAddress(module_handle, "NtQuerySystemInformation")); 13 | 14 | } 15 | -------------------------------------------------------------------------------- /mapper/ntdll.hpp: -------------------------------------------------------------------------------- 1 | #pragma once 2 | #include "logger.hpp" 3 | 4 | #include 5 | #include 6 | #include 7 | 8 | using NtCreateSection_t = NTSTATUS(NTAPI*)( 9 | PHANDLE sectionHandle, 10 | ULONG DesiredAccess, 11 | POBJECT_ATTRIBUTES ObjectAttributes OPTIONAL, 12 | PLARGE_INTEGER MaximumSize OPTIONAL, 13 | ULONG PageAttributess, 14 | ULONG SectionAttributes, 15 | HANDLE FileHandle OPTIONAL); 16 | 17 | using NtMapViewOfSection_t = NTSTATUS(NTAPI*)( 18 | HANDLE SectionHandle, 19 | HANDLE ProcessHandle, 20 | PVOID *BaseAddress, 21 | ULONG_PTR ZeroBits, 22 | SIZE_T CommitSize, 23 | PLARGE_INTEGER SectionOffset, 24 | PSIZE_T ViewSize, 25 | int InheritDisposition, 26 | ULONG AllocationType, 27 | ULONG Win32Protect); 28 | 29 | using NtQuerySystemInformation_t = NTSTATUS(NTAPI*)( 30 | SYSTEM_INFORMATION_CLASS SystemInformationClass, 31 | PVOID SystemInformation, 32 | ULONG SystemInformationLength, 33 | ULONG* ReturnLength); 34 | 35 | namespace ntdll 36 | { 37 | void initialise() noexcept; 38 | extern NtCreateSection_t NtCreateSection; 39 | extern NtMapViewOfSection_t NtMapViewOfSection; 40 | extern NtQuerySystemInformation_t NtQuerySystemInformation; 41 | 42 | 43 | // NATIVE ENUMERATORS 44 | template 45 | void enumerate_processes(Fn callback) noexcept 46 | { 47 | constexpr auto size_mismatch = 0xC0000004; 48 | constexpr auto process_type = SystemProcessInformation; 49 | 50 | // QUERY SIZE 51 | auto allocation = std::make_unique(0x1); 52 | std::uint32_t size_needed = 0; 53 | const auto size_needed_pointer = reinterpret_cast(&size_needed); 54 | if (ntdll::NtQuerySystemInformation(process_type, allocation.get(), 0x1, size_needed_pointer) != size_mismatch) 55 | { 56 | logger::log_error("NtQuerySystemInformation undefined behaviour."); 57 | return; 58 | } 59 | 60 | allocation = std::make_unique(size_needed); 61 | auto info = reinterpret_cast(allocation.get()); 62 | 63 | // QUERY DATA 64 | if (auto result = ntdll::NtQuerySystemInformation(process_type, info, size_needed, size_needed_pointer); 65 | result != 0x00) 66 | { 67 | logger::log_error("NtQuerySystemInformation failed - SYSTEM_PROCESS_INFORMATION"); 68 | logger::log_formatted("Result", result, true); 69 | return; 70 | } 71 | 72 | for ( 73 | auto info_casted = reinterpret_cast(info); 74 | info->NextEntryOffset; 75 | info = reinterpret_cast(info_casted + info->NextEntryOffset), 76 | info_casted = reinterpret_cast(info)) 77 | { 78 | if (callback(info)) 79 | break; 80 | } 81 | } 82 | 83 | template 84 | void enumerate_threads(Fn callback) noexcept 85 | { 86 | ntdll::enumerate_processes([=](SYSTEM_PROCESS_INFORMATION* info) { 87 | const auto info_casted = reinterpret_cast(info); 88 | const auto thread_info = reinterpret_cast(info_casted + sizeof(SYSTEM_PROCESS_INFORMATION)); 89 | for (std::uint32_t thread_index = 0; thread_index < info->NumberOfThreads; ++thread_index) 90 | { 91 | if (callback(&thread_info[thread_index])) 92 | return true; 93 | } 94 | 95 | return false; 96 | }); 97 | } 98 | } -------------------------------------------------------------------------------- /mapper/pe_section.hpp: -------------------------------------------------------------------------------- 1 | #pragma once 2 | #include 3 | #include 4 | 5 | class pe_section 6 | { 7 | public: 8 | explicit pe_section(const IMAGE_SECTION_HEADER& header) noexcept : m_header(header) {}; 9 | 10 | 11 | // SECTION FLAGS 12 | enum data_section_flags : std::uint32_t 13 | { 14 | type_reg = 0x00000000, 15 | type_d_Sect = 0x00000001, 16 | type_no_load = 0x00000002, 17 | type_group = 0x00000004, 18 | type_no_padded = 0x00000008, 19 | type_copy = 0x00000010, 20 | content_code = 0x00000020, 21 | content_initialized_data = 0x00000040, 22 | content_uninitialized_data = 0x00000080, 23 | link_other = 0x00000100, 24 | link_info = 0x00000200, 25 | type_over = 0x00000400, 26 | link_remove = 0x00000800, 27 | link_com_dat = 0x00001000, 28 | no_defer_spec_exceptions = 0x00004000, 29 | relative_gp = 0x00008000, 30 | mem_purgeable = 0x00020000, 31 | memory_16_bit = 0x00020000, 32 | memory_locked = 0x00040000, 33 | memory_preload = 0x00080000, 34 | align_1_bytes = 0x00100000, 35 | align_2_bytes = 0x00200000, 36 | align_4_bytes = 0x00300000, 37 | align_8_bytes = 0x00400000, 38 | align_16_bytes = 0x00500000, 39 | align_32_bytes = 0x00600000, 40 | align_64_bytes = 0x00700000, 41 | align_128_bytes = 0x00800000, 42 | align_256_bytes = 0x00900000, 43 | align_512_bytes = 0x00A00000, 44 | align_1024_bytes = 0x00B00000, 45 | align_2048_bytes = 0x00C00000, 46 | align_4096_bytes = 0x00D00000, 47 | align_8192_bytes = 0x00E00000, 48 | link_extended_relocation_overflow = 0x01000000, 49 | memory_discardable = 0x02000000, 50 | memory_not_cached = 0x04000000, 51 | memory_not_paged = 0x08000000, 52 | memory_shared = 0x10000000, 53 | memory_execute = 0x20000000, 54 | memory_read = 0x40000000, 55 | memory_write = 0x80000000 56 | }; 57 | 58 | const bool is_writable() const noexcept 59 | { 60 | return this->has_flag_set(data_section_flags::memory_write); 61 | } 62 | const bool is_readable() const noexcept 63 | { 64 | return this->has_flag_set(data_section_flags::memory_read); 65 | } 66 | const bool is_executable() const noexcept 67 | { 68 | return this->has_flag_set(data_section_flags::memory_execute); 69 | } 70 | const bool is_discardable() const noexcept 71 | { 72 | return this->has_flag_set(data_section_flags::memory_discardable); 73 | } 74 | const bool has_flag_set(const data_section_flags& flag) const noexcept 75 | { 76 | return (this->raw_header().Characteristics & flag) == flag; 77 | } 78 | 79 | // SECTION INFORMATION 80 | const DWORD& virtual_address() const noexcept 81 | { 82 | return this->m_header.VirtualAddress; 83 | } 84 | const DWORD& virtual_size() const noexcept 85 | { 86 | return this->m_header.Misc.VirtualSize; 87 | } 88 | const DWORD& raw_data_offset() const noexcept 89 | { 90 | return this->m_header.PointerToRawData; 91 | } 92 | const DWORD& raw_size() const noexcept 93 | { 94 | return this->m_header.SizeOfRawData; 95 | } 96 | 97 | const IMAGE_SECTION_HEADER& raw_header() const noexcept 98 | { 99 | return this->m_header; 100 | } 101 | 102 | private: 103 | IMAGE_SECTION_HEADER m_header; 104 | }; -------------------------------------------------------------------------------- /mapper/portable_executable.cpp: -------------------------------------------------------------------------------- 1 | #include "portable_executable.hpp" 2 | #include "transformer.hpp" 3 | #include "logger.hpp" 4 | 5 | #include 6 | #include 7 | 8 | portable_executable::portable_executable(const std::vector& new_buffer) noexcept : m_buffer(new_buffer) 9 | { 10 | // READ HEADERS 11 | if (this->m_buffer.data()) 12 | { 13 | const auto buffer_address = this->m_buffer.data(); 14 | 15 | this->m_dos_header = reinterpret_cast(buffer_address); 16 | this->m_nt_headers = reinterpret_cast(buffer_address + this->get_dos_header()->e_lfanew); 17 | this->m_file_header = this->get_nt_headers()->FileHeader; 18 | this->m_optional_header = this->get_nt_headers()->OptionalHeader; 19 | 20 | // PARSE IMAGE SECTIONS FOR LATER USAGE 21 | parse_sections(); 22 | } 23 | } 24 | 25 | const IMAGE_DOS_HEADER* portable_executable::get_dos_header() const noexcept 26 | { 27 | return this->m_dos_header; 28 | } 29 | 30 | const IMAGE_NT_HEADERS* portable_executable::get_nt_headers() const noexcept 31 | { 32 | return this->m_nt_headers; 33 | } 34 | 35 | const IMAGE_FILE_HEADER portable_executable::get_file_header() const noexcept 36 | { 37 | return this->m_file_header; 38 | } 39 | 40 | const IMAGE_OPTIONAL_HEADER portable_executable::get_optional_header() const noexcept 41 | { 42 | return this->m_optional_header; 43 | } 44 | 45 | const std::uintptr_t portable_executable::get_image_base() const noexcept 46 | { 47 | return this->m_optional_header.ImageBase; 48 | } 49 | 50 | const section_list& portable_executable::get_sections() const noexcept 51 | { 52 | return this->m_sections; 53 | } 54 | 55 | const std::vector& portable_executable::get_buffer() const noexcept 56 | { 57 | return this->m_buffer; 58 | } 59 | 60 | void portable_executable::parse_sections() noexcept 61 | { 62 | const auto section_pointer = reinterpret_cast(this->get_nt_headers() + 1); 63 | for (auto index = 0; index < this->get_file_header().NumberOfSections; index++) 64 | this->m_sections.push_back(pe_section(section_pointer[index])); 65 | } 66 | 67 | relocation_list portable_executable::get_relocations(std::uintptr_t image_base) const noexcept 68 | { 69 | relocation_list result; 70 | auto section = this->get_optional_header().DataDirectory[IMAGE_DIRECTORY_ENTRY_BASERELOC]; 71 | auto base_relocation = reinterpret_cast(image_base + section.VirtualAddress); 72 | auto end_relocation = reinterpret_cast(base_relocation) + section.Size; 73 | auto reloc = reinterpret_cast(base_relocation); 74 | 75 | while (reinterpret_cast(reloc) < end_relocation && reloc->block_size > 0) 76 | { 77 | auto count = (reloc->block_size - 8) >> 1; 78 | for (size_t relocation_index = 0; relocation_index < count; ++relocation_index) 79 | { 80 | auto type = reloc->item[relocation_index].type; 81 | if (type == IMAGE_REL_BASED_HIGHLOW || type == IMAGE_REL_BASED_DIR64) 82 | result.emplace_back(*reloc, reloc->item[relocation_index]); 83 | } 84 | 85 | reloc = reinterpret_cast(reinterpret_cast(reloc) + reloc->block_size); 86 | } 87 | 88 | return result; 89 | } 90 | 91 | import_list portable_executable::get_imports(std::uintptr_t image_base) const noexcept 92 | { 93 | import_list import_modules; 94 | 95 | auto section = this->get_optional_header().DataDirectory[IMAGE_DIRECTORY_ENTRY_IMPORT]; 96 | 97 | if (section.VirtualAddress == 0x00 || section.Size == 0x00) 98 | return import_modules; 99 | 100 | auto import_table = reinterpret_cast(image_base + section.VirtualAddress); 101 | 102 | for (std::uint32_t previous_name = 0; // NAMES ARE IN MEMORY ORDER 103 | previous_name < import_table->Name; 104 | previous_name = import_table->Name, ++import_table) 105 | { 106 | auto module_name = std::string(reinterpret_cast(image_base + (std::uintptr_t)import_table->Name)); 107 | 108 | if (module_name.empty()) 109 | { 110 | logger::log_error("Empty module name in import table"); 111 | } 112 | 113 | 114 | // CONVERT TO LOWER 115 | transformer::string_to_lower(module_name); 116 | 117 | auto entry = reinterpret_cast(image_base + import_table->OriginalFirstThunk); 118 | for (std::uintptr_t index = 0; entry->u1.AddressOfData; index += sizeof(std::uintptr_t), ++entry) 119 | { 120 | auto import_by_name = reinterpret_cast(image_base + entry->u1.AddressOfData); 121 | 122 | import_data data; 123 | data.function_rva = import_table->FirstThunk + index; 124 | 125 | if (entry->u1.Ordinal < IMAGE_ORDINAL_FLAG64 && import_by_name->Name[0]) 126 | data.name = reinterpret_cast(import_by_name->Name); // IMPORT BY NAME 127 | else 128 | data.ordinal = IMAGE_ORDINAL64(entry->u1.AddressOfData); // IMPORT BY ORDINAL 129 | 130 | import_modules[module_name].emplace_back(data); 131 | } 132 | } 133 | 134 | return import_modules; 135 | } 136 | 137 | // THX DAAX <3 138 | export_list portable_executable::get_exports(std::uintptr_t image_base) const noexcept 139 | { 140 | export_list exports; 141 | 142 | auto section = this->get_optional_header().DataDirectory[IMAGE_DIRECTORY_ENTRY_EXPORT]; 143 | auto export_dir = reinterpret_cast(image_base + section.VirtualAddress); 144 | 145 | for (unsigned int iter = 0; iter < export_dir->NumberOfFunctions; ++iter) 146 | { 147 | export_data data = { 0 }; 148 | data.name = reinterpret_cast(image_base + reinterpret_cast(image_base + export_dir->AddressOfNames)[iter]); 149 | data.ordinal = reinterpret_cast(image_base + export_dir->AddressOfNameOrdinals)[iter]; 150 | data.function_rva = image_base + reinterpret_cast(image_base + export_dir->AddressOfFunctions)[iter]; 151 | 152 | exports[data.name].emplace_back(data); 153 | } 154 | 155 | return exports; 156 | } 157 | -------------------------------------------------------------------------------- /mapper/portable_executable.hpp: -------------------------------------------------------------------------------- 1 | #pragma once 2 | #include 3 | #include 4 | #include 5 | #include 6 | 7 | #include "pe_section.hpp" 8 | 9 | struct reloc_item 10 | { 11 | std::uint16_t offset : 12; 12 | std::uint16_t type : 4; 13 | 14 | std::uint16_t get_offset() noexcept 15 | { 16 | return offset % 4096; 17 | } 18 | }; 19 | struct reloc_data 20 | { 21 | std::uint32_t page_rva; 22 | std::uint32_t block_size; 23 | reloc_item item[1]; 24 | }; 25 | 26 | struct import_data 27 | { 28 | std::string name; 29 | std::uintptr_t function_rva; 30 | std::uintptr_t ordinal = 0; 31 | }; 32 | 33 | struct export_data 34 | { 35 | std::string name; 36 | std::uintptr_t function_rva; 37 | uint16_t ordinal; 38 | }; 39 | 40 | using relocation_list = std::vector>; 41 | using section_list = std::vector; 42 | using import_list = std::unordered_map>; 43 | using export_list = std::unordered_map>; 44 | 45 | class portable_executable 46 | { 47 | public: 48 | portable_executable() {}; 49 | explicit portable_executable(const std::vector& new_buffer) noexcept; 50 | 51 | // INFORMATION 52 | const IMAGE_DOS_HEADER* get_dos_header() const noexcept; 53 | const IMAGE_NT_HEADERS* get_nt_headers() const noexcept; 54 | const IMAGE_FILE_HEADER get_file_header() const noexcept; 55 | const IMAGE_OPTIONAL_HEADER get_optional_header() const noexcept; 56 | const std::uintptr_t get_image_base() const noexcept; 57 | 58 | // RESOURCES 59 | const std::vector& get_buffer() const noexcept; 60 | const section_list& get_sections() const noexcept; 61 | 62 | relocation_list get_relocations(std::uintptr_t image_base) const noexcept; 63 | import_list get_imports(std::uintptr_t image_base) const noexcept; 64 | export_list get_exports(std::uintptr_t image_base) const noexcept; 65 | 66 | private: 67 | void parse_sections() noexcept; 68 | IMAGE_DOS_HEADER* m_dos_header; 69 | IMAGE_NT_HEADERS* m_nt_headers; 70 | IMAGE_OPTIONAL_HEADER m_optional_header; 71 | IMAGE_FILE_HEADER m_file_header; 72 | std::vector m_buffer; 73 | section_list m_sections; 74 | }; -------------------------------------------------------------------------------- /mapper/process.cpp: -------------------------------------------------------------------------------- 1 | #include "transformer.hpp" 2 | #include "process.hpp" 3 | #include "logger.hpp" 4 | #include "ntdll.hpp" 5 | #include "cast.hpp" 6 | 7 | #include 8 | #include 9 | #include 10 | #include 11 | 12 | native::process native::process::current_process() noexcept 13 | { 14 | return process(reinterpret_cast(-1)); 15 | } 16 | 17 | std::uint32_t native::process::id_from_name(std::string_view process_name) noexcept 18 | { 19 | DWORD process_list[516], bytes_needed; 20 | if (K32EnumProcesses(process_list, sizeof(process_list), &bytes_needed)) 21 | { 22 | for (size_t index = 0; index < bytes_needed / sizeof(std::uint32_t); index++) 23 | { 24 | auto proc = process(process_list[index], PROCESS_ALL_ACCESS); 25 | 26 | if (proc && process_name == proc.get_name()) 27 | return process_list[index]; 28 | } 29 | } 30 | 31 | logger::log_error("Process not found"); 32 | return 0x00; 33 | } 34 | 35 | MEMORY_BASIC_INFORMATION native::process::virtual_query(const std::uintptr_t address) const noexcept 36 | { 37 | MEMORY_BASIC_INFORMATION mbi; 38 | 39 | VirtualQueryEx(this->handle().unsafe_handle(), reinterpret_cast(address), &mbi, sizeof(MEMORY_BASIC_INFORMATION)); 40 | 41 | return mbi; 42 | } 43 | 44 | std::uintptr_t native::process::raw_allocate(const SIZE_T virtual_size, const std::uintptr_t address) noexcept 45 | { 46 | return reinterpret_cast( 47 | VirtualAllocEx(this->handle().unsafe_handle(), reinterpret_cast(address), virtual_size, MEM_COMMIT, PAGE_EXECUTE_READWRITE) 48 | ); 49 | } 50 | 51 | bool native::process::free_memory(const std::uintptr_t address) noexcept 52 | { 53 | return VirtualFreeEx(this->handle().unsafe_handle(), reinterpret_cast(address), NULL, MEM_RELEASE); 54 | } 55 | 56 | 57 | bool native::process::read_raw_memory(const void* buffer, const std::uintptr_t address, const std::size_t size) const noexcept 58 | { 59 | return ReadProcessMemory( 60 | this->handle().unsafe_handle(), 61 | reinterpret_cast(address), 62 | const_cast(buffer), 63 | size, 64 | nullptr); 65 | } 66 | 67 | bool native::process::write_raw_memory(const void* buffer, const std::uintptr_t address, const std::size_t size) noexcept 68 | { 69 | return WriteProcessMemory( 70 | this->handle().unsafe_handle(), 71 | reinterpret_cast(address), 72 | buffer, 73 | size, 74 | nullptr); 75 | } 76 | 77 | bool native::process::virtual_protect( 78 | const std::uintptr_t address, 79 | const std::uint32_t protect, 80 | std::uint32_t* old_protect, 81 | const std::size_t page_size) noexcept 82 | { 83 | return VirtualProtectEx( 84 | this->handle().unsafe_handle(), 85 | reinterpret_cast(address), 86 | page_size, 87 | protect, 88 | reinterpret_cast(old_protect)); 89 | } 90 | 91 | std::uintptr_t native::process::map(const memory_section& section) noexcept 92 | { 93 | void* base_address = nullptr; 94 | SIZE_T view_size = section.size(); 95 | 96 | auto result = ntdll::NtMapViewOfSection( 97 | section.handle().unsafe_handle(), 98 | this->handle().unsafe_handle(), 99 | &base_address, 100 | NULL, NULL, NULL, 101 | &view_size, 102 | 2, 0, 103 | section.protection()); 104 | 105 | if (!NT_SUCCESS(result)) 106 | { 107 | logger::log_error("NtMapViewOfSection failed"); 108 | logger::log_formatted("Error code", result, true); 109 | } 110 | 111 | return reinterpret_cast(base_address); 112 | } 113 | 114 | HWND native::process::get_main_window() const noexcept 115 | { 116 | // SETUP CONTAINER 117 | using window_data_t = std::pair; 118 | window_data_t window_data = window_data_t{ this->get_id(), 0x00 }; 119 | 120 | logger::log_formatted("Process id", window_data.first, false); 121 | 122 | // ENUMERATE WINDOWS TO FIND 123 | EnumWindows([](HWND handle, LPARAM param) -> BOOL 124 | { 125 | auto data = reinterpret_cast(param); 126 | 127 | logger::log_formatted("Handle", handle, false); 128 | 129 | std::uint32_t process_id = 0; 130 | if (!GetWindowThreadProcessId(handle, reinterpret_cast(&process_id)) || process_id != data->first) 131 | return TRUE; // CONTINUE 132 | 133 | SetLastError(static_cast(-1)); 134 | data->second = handle; 135 | return FALSE; 136 | }, reinterpret_cast(&window_data)); 137 | 138 | logger::log_formatted("Main", window_data.second, false); 139 | 140 | // RETURN WINDOW 141 | return window_data.second; 142 | } 143 | 144 | std::uint32_t native::process::get_id() const noexcept 145 | { 146 | return GetProcessId(this->handle().unsafe_handle()); 147 | } 148 | 149 | native::process::module_list_t native::process::get_modules() const noexcept 150 | { 151 | native::process::module_list_t result{}; 152 | //std::array modules{}; 153 | // 154 | //std::uint32_t size_needed; 155 | //if (!EnumProcessModulesEx( 156 | // this->handle().unsafe_handle(), 157 | // modules.data(), 158 | // static_cast(modules.size()), 159 | // reinterpret_cast(&size_needed), LIST_MODULES_ALL)) 160 | //{ 161 | // return result; 162 | //} 163 | // 164 | //for (auto module_index = 0; module_index < size_needed / sizeof(HMODULE); module_index++) 165 | //{ 166 | // // INITIALISE STRING OF SIZE MAX_PATH (260) 167 | // std::string module_name(MAX_PATH, '\00'); 168 | // 169 | // // GET MODULE NAME 170 | // GetModuleBaseNameA( 171 | // this->handle().unsafe_handle(), 172 | // modules.at(module_index), 173 | // const_cast(module_name.c_str()), 174 | // static_cast(module_name.size())); 175 | // 176 | // // MAKE CHARACTERS LOWERCASE 177 | // transformer::string_to_lower(module_name); 178 | // 179 | // // TRUNCATE SIZE TO NULL TERMINATOR 180 | // transformer::truncate(module_name); 181 | // 182 | // // SET ENTRY 183 | // result[module_name] = reinterpret_cast(modules.at(module_index)); 184 | //} 185 | 186 | 187 | const auto snapshot_handle = CreateToolhelp32Snapshot(TH32CS_SNAPMODULE, this->get_id()); 188 | 189 | MODULEENTRY32 module_entry{}; 190 | module_entry.dwSize = sizeof(MODULEENTRY32); 191 | 192 | if (!Module32FirstW(snapshot_handle, &module_entry)) 193 | { 194 | logger::log_error("Failed to get module"); 195 | return result; 196 | } 197 | 198 | auto success = TRUE; 199 | 200 | wstring_converter_t converter; 201 | 202 | for (; success; success = Module32NextW(snapshot_handle, &module_entry)) 203 | { 204 | // INITIALISE STRING OF SIZE MAX_PATH (260) 205 | std::wstring module_name(module_entry.szModule); 206 | 207 | // MAKE CHARACTERS LOWERCASE 208 | transformer::string_to_lower(module_name); 209 | 210 | // TRUNCATE SIZE TO NULL TERMINATOR 211 | transformer::truncate(module_name); 212 | 213 | // CONVERT TO STRING 214 | const auto narrow_string = converter.to_bytes(module_name); 215 | 216 | // SET ENTRY 217 | result[narrow_string] = reinterpret_cast(module_entry.modBaseAddr); 218 | } 219 | 220 | return result; 221 | } 222 | 223 | std::string native::process::get_name() const noexcept 224 | { 225 | char buffer[MAX_PATH]; 226 | GetModuleBaseNameA(this->handle().unsafe_handle(), nullptr, buffer, MAX_PATH); 227 | 228 | return std::string(buffer); 229 | } 230 | 231 | native::process::module_export native::process::get_module_export(std::uintptr_t module_handle, const char* function_ordinal) const noexcept 232 | { 233 | IMAGE_DOS_HEADER dos_header; 234 | IMAGE_NT_HEADERS64 nt_header; 235 | this->read_memory(&dos_header, module_handle); 236 | this->read_memory(&nt_header, module_handle + dos_header.e_lfanew); 237 | 238 | auto export_base = nt_header.OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_EXPORT].VirtualAddress; 239 | auto export_base_size = nt_header.OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_EXPORT].Size; 240 | if (export_base == 0x00 || export_base_size == 0x00) // CONTAINS EXPORTED FUNCTIONS? 241 | { 242 | logger::log_error("Module does not contain exports!"); 243 | return native::process::module_export(0x00); 244 | } 245 | 246 | auto export_data_raw = std::make_unique(export_base_size); 247 | auto export_data = reinterpret_cast(export_data_raw.get()); 248 | 249 | // READ EXPORTED DATA FROM TARGET PROCESS FOR LATER PROCESSING 250 | if (!this->read_raw_memory(export_data, module_handle + export_base, export_base_size)) 251 | logger::log_error("failed to read export data"); 252 | 253 | // BLACKBONE HAD THIS ... NEVER EXPERIENCED THIS BUT WHO KNOWS? 254 | if (export_base_size <= sizeof(IMAGE_EXPORT_DIRECTORY)) 255 | { 256 | export_base_size = static_cast(export_data->AddressOfNameOrdinals - export_base 257 | + max(export_data->NumberOfFunctions, export_data->NumberOfNames) * 255); 258 | 259 | // UPDATE EXPORT DATA 260 | export_data_raw = std::make_unique(export_base_size); 261 | export_data = reinterpret_cast(export_data_raw.get()); 262 | 263 | if (!this->read_raw_memory(export_data, module_handle + export_base, export_base_size)) 264 | logger::log_error("failed to read export data"); 265 | } 266 | 267 | // NO EXPORTED FUNCTIONS? DID WE FUCK UP? 268 | if (export_data->NumberOfFunctions <= 0) 269 | logger::log_error("No exports found!"); 270 | 271 | // GET DATA FROM READ MEMORY 272 | const auto delta = reinterpret_cast(export_data) - export_base; 273 | const auto address_of_ordinals = reinterpret_cast(export_data->AddressOfNameOrdinals + delta); 274 | const auto address_of_names = reinterpret_cast(export_data->AddressOfNames + delta); 275 | const auto address_of_functions = reinterpret_cast(export_data->AddressOfFunctions + delta); 276 | 277 | // ITERATE EXPORTED FUNCTIONS 278 | const auto ptr_function_ordinal = reinterpret_cast(function_ordinal); 279 | for (size_t export_index = 0; export_index < export_data->NumberOfFunctions; export_index++) 280 | { 281 | const auto is_import_by_ordinal = ptr_function_ordinal <= 0xFFFF; 282 | 283 | // GET EXPORT INFORMATION 284 | const auto ordinal = static_cast(is_import_by_ordinal ? export_index : address_of_ordinals[export_index]); 285 | std::string function_name = reinterpret_cast(address_of_names[export_index] + delta); 286 | 287 | // IS IT THE FUNCTION WE ASKED FOR? 288 | const auto found_via_ordinal = 289 | is_import_by_ordinal && 290 | static_cast(ptr_function_ordinal) == (ordinal + export_data->Base); 291 | 292 | const auto found_via_name = 293 | !is_import_by_ordinal && function_name == function_ordinal; 294 | 295 | if (!found_via_ordinal && !found_via_name) 296 | continue; 297 | 298 | // FORWARDED EXPORT? 299 | // IF FUNCTION POINTER IS INSIDE THE EXPORT DIRECTORY, IT IS *NOT* A FUNCTION POINTER! 300 | // FUCKING SHIT MSVCPxxx 301 | // FUCK YOU 302 | const auto function_pointer = module_handle + address_of_functions[ordinal]; 303 | const auto directory_start = module_handle + export_base; 304 | const auto directory_end = module_handle + export_base + export_base_size; 305 | if (function_pointer >= directory_start && function_pointer <= directory_end) 306 | { 307 | // READ FORWARD 308 | std::byte forwarded_name[50] = {}; 309 | this->read_raw_memory(forwarded_name, function_pointer, sizeof(forwarded_name)); 310 | 311 | // PARSE FUNCTION NAME 312 | std::string forward(reinterpret_cast(forwarded_name)); 313 | function_name = forward.substr(forward.find(".") + 1, function_name.npos); 314 | 315 | // PARSE LIBRARY NAME 316 | auto library_name = forward.substr(0, forward.find(".")) + ".dll"; 317 | transformer::string_to_lower(library_name); 318 | 319 | // FIND FORWARDED MODULE 320 | auto modules = this->get_modules(); 321 | const auto search = modules.find(library_name); 322 | if (search == modules.end()) 323 | { 324 | logger::log_error("Forwarded module not loaded."); 325 | return native::process::module_export(library_name, function_name); 326 | } 327 | 328 | // RECURSIVELY HANDLE FORWARDED MODULE :) 329 | return this->get_module_export(search->second, function_name.c_str()); 330 | } 331 | 332 | return native::process::module_export(function_pointer); 333 | } 334 | 335 | logger::log_error("Export not found!"); 336 | return native::process::module_export(0x00); 337 | } 338 | 339 | native::thread native::process::create_thread(const std::uintptr_t address, const std::uintptr_t argument) noexcept 340 | { 341 | const auto casted_function = reinterpret_cast(address); 342 | const auto casted_argument = reinterpret_cast(argument); 343 | 344 | const auto thread_handle = CreateRemoteThread( 345 | this->handle().unsafe_handle(), 346 | nullptr, 0x00, 347 | casted_function, casted_argument, 348 | 0x00, nullptr); 349 | 350 | return native::thread(thread_handle); 351 | } 352 | 353 | std::vector native::process::threads() const noexcept 354 | { 355 | std::vector thread_list{}; 356 | 357 | const auto current_pid = this->get_id(); 358 | 359 | ntdll::enumerate_threads([=, &thread_list](SYSTEM_THREAD_INFORMATION* info) 360 | { 361 | if (cast::pointer_convert(info->ClientId.UniqueProcess) != current_pid) 362 | return false; 363 | 364 | const auto this_thread = info->ClientId.UniqueThread; 365 | auto handle = OpenThread(THREAD_ALL_ACCESS, false, cast::pointer_convert(this_thread)); 366 | 367 | if (handle == INVALID_HANDLE_VALUE) 368 | { 369 | logger::log_error("Failed to open handle to thread."); 370 | logger::log_formatted("Thread Id", this_thread, true); 371 | return false; 372 | } 373 | 374 | thread_list.emplace_back(handle, *info); 375 | return false; 376 | }); 377 | 378 | return thread_list; 379 | } 380 | 381 | const safe_handle& native::process::handle() const noexcept 382 | { 383 | return this->m_handle; 384 | } 385 | -------------------------------------------------------------------------------- /mapper/process.hpp: -------------------------------------------------------------------------------- 1 | #pragma once 2 | #include "memory_section.hpp" 3 | #include "safe_handle.hpp" 4 | #include "thread.hpp" 5 | 6 | #include 7 | #include 8 | #include 9 | #include 10 | #include 11 | 12 | #pragma warning(disable:4996) // DEPRECATED LIBRARY :( 13 | using wstring_converter_t = std::wstring_convert, wchar_t>; 14 | 15 | namespace native 16 | { 17 | class process 18 | { 19 | public: 20 | process() noexcept { } 21 | 22 | explicit process(HANDLE handle) noexcept : m_handle(handle) {} 23 | 24 | explicit process(std::uint32_t id, std::uint32_t desired_access) noexcept : 25 | m_handle(safe_handle(OpenProcess(desired_access, false, id))) { } 26 | 27 | explicit process(std::string_view process_name, std::uint32_t desired_access) noexcept 28 | { 29 | const auto process_id = native::process::id_from_name(process_name); 30 | this->m_handle = safe_handle(OpenProcess(desired_access, false, process_id)); 31 | } 32 | 33 | explicit operator bool() const noexcept 34 | { 35 | return this->handle().unsafe_handle() != nullptr; 36 | } 37 | 38 | // STATICS 39 | static process current_process() noexcept; 40 | static std::uint32_t id_from_name(std::string_view process_name) noexcept; 41 | 42 | // MEMORY 43 | bool free_memory(const uintptr_t address) noexcept; 44 | std::uintptr_t map(const memory_section& section) noexcept; 45 | MEMORY_BASIC_INFORMATION virtual_query(const std::uintptr_t address) const noexcept; 46 | std::uintptr_t raw_allocate(const SIZE_T virtual_size, const std::uintptr_t address = 0) noexcept; 47 | bool write_raw_memory(const void* buffer, const std::uintptr_t address, const std::size_t size) noexcept; 48 | bool read_raw_memory(const void* buffer, const std::uintptr_t address, const std::size_t size) const noexcept; 49 | bool virtual_protect(const std::uintptr_t address, 50 | const std::uint32_t protect, 51 | std::uint32_t* old_protect, 52 | const std::size_t page_size) noexcept; 53 | 54 | template 55 | std::uintptr_t allocate_and_write(const T& buffer) noexcept 56 | { 57 | auto buffer_pointer = allocate(buffer); 58 | write_memory(buffer, buffer_pointer); 59 | return buffer_pointer; 60 | } 61 | 62 | template 63 | std::uintptr_t allocate() noexcept 64 | { 65 | return raw_allocate(sizeof(T)); 66 | } 67 | 68 | template 69 | bool read_memory(T* buffer, const std::uintptr_t address) const noexcept 70 | { 71 | return read_raw_memory(buffer, address, sizeof(T)); 72 | } 73 | 74 | template 75 | bool write_memory(const T& buffer, const std::uintptr_t address) noexcept 76 | { 77 | std::uint32_t old_protect; 78 | if (!this->virtual_protect(address, PAGE_EXECUTE_READWRITE, &old_protect, sizeof(T))) 79 | { 80 | //logger::log_error("Failed to set PAGE_EXECUTE_READWRITE"); 81 | //logger::log_formatted("Last error", GetLastError(), true); 82 | //return false; 83 | } 84 | 85 | if (!write_raw_memory(reinterpret_cast(const_cast(&buffer)), address, sizeof(T))) 86 | { 87 | //logger::log_error("Failed to write memory"); 88 | //logger::log_formatted("Last error", GetLastError(), true); 89 | return false; 90 | } 91 | 92 | if (!this->virtual_protect(old_protect, PAGE_EXECUTE_READWRITE, &old_protect, sizeof(T))) 93 | { 94 | //logger::log_error("Failed to reset page protection"); 95 | //logger::log_formatted("Last error", GetLastError(), true); 96 | //return false; 97 | } 98 | 99 | return true; 100 | } 101 | 102 | // INFORMATION 103 | HWND get_main_window() const noexcept; 104 | std::uint32_t get_id() const noexcept; 105 | 106 | using module_list_t = std::unordered_map; 107 | module_list_t get_modules() const noexcept; 108 | std::string get_name() const noexcept; 109 | 110 | // PARSE EXPORTS 111 | struct module_export 112 | { 113 | // CTOR FROM FUNCTION POINTER 114 | module_export(std::uintptr_t new_function) : 115 | function(new_function), forwarded(false), forwarded_library(), forwarded_name() {} 116 | 117 | // CTOR FROM FORWARD INFO 118 | module_export(std::string_view library, std::string_view name) : 119 | function(0x00), forwarded(true), forwarded_library(library), forwarded_name(name) {} 120 | 121 | std::uintptr_t function; 122 | bool forwarded; 123 | std::string forwarded_library; 124 | std::string forwarded_name; 125 | }; 126 | native::process::module_export get_module_export(std::uintptr_t module_handle, const char* function_ordinal) const noexcept; 127 | 128 | // THREAD 129 | native::thread create_thread(const std::uintptr_t address, const std::uintptr_t argument = 0) noexcept; 130 | 131 | std::vector threads() const noexcept; 132 | 133 | 134 | const safe_handle& handle() const noexcept; 135 | 136 | private: 137 | safe_handle m_handle; 138 | }; 139 | } -------------------------------------------------------------------------------- /mapper/safe_handle.hpp: -------------------------------------------------------------------------------- 1 | #pragma once 2 | #include 3 | #include 4 | 5 | class safe_handle 6 | { 7 | public: 8 | safe_handle() : m_handle(nullptr) {} 9 | explicit safe_handle(HANDLE new_handle) noexcept : m_handle(new_handle) {} 10 | ~safe_handle() noexcept 11 | { 12 | if (this->unsafe_handle()) 13 | { 14 | //logger::log_formatted("Closing", this->handle, true); 15 | CloseHandle(this->unsafe_handle()); 16 | } 17 | } 18 | 19 | 20 | // EXPLICITELY DELETE COPY FUNCTIONS TO PREVENT ANY 21 | // COPYING OF THE HANDLE OBJECT 22 | 23 | // COPY CONSTRUCTOR 24 | safe_handle(const safe_handle& that) = delete; 25 | 26 | // COPY ASSIGNMENT OPERATOR 27 | safe_handle& operator= (const safe_handle& other) = delete; 28 | 29 | // MOVE CONSTRUCTOR 30 | safe_handle(safe_handle&& other) noexcept : m_handle(other.m_handle) 31 | { 32 | other.invalidate(); 33 | } 34 | 35 | // MOVE ASSIGNMENT OPERATOR 36 | safe_handle& operator= (safe_handle&& other) noexcept 37 | { 38 | this->m_handle = other.m_handle; // COPY TO NEW INSTANCE AND NULL OLD 39 | other.invalidate(); 40 | return *this; 41 | } 42 | 43 | explicit operator bool() const noexcept 44 | { 45 | return this->unsafe_handle() != nullptr; 46 | } 47 | 48 | inline auto unsafe_handle() const noexcept -> const HANDLE& 49 | { 50 | return this->m_handle; 51 | } 52 | 53 | inline auto invalidate() noexcept -> void 54 | { 55 | this->m_handle = nullptr; 56 | } 57 | 58 | private: 59 | HANDLE m_handle; 60 | }; -------------------------------------------------------------------------------- /mapper/safe_memory.hpp: -------------------------------------------------------------------------------- 1 | #pragma once 2 | #include 3 | #include 4 | 5 | #include "process.hpp" 6 | #include "logger.hpp" 7 | 8 | class safe_memory 9 | { 10 | public: 11 | safe_memory() {} 12 | explicit safe_memory(native::process* process, std::uintptr_t memory) noexcept 13 | : m_process(process), m_memory(memory) {} 14 | ~safe_memory() 15 | { 16 | // IF VALID COPY OF SAFE_MEMORY: FREE MEMORY 17 | if (this->operator bool()) 18 | { 19 | logger::log_formatted("Freeing", this->memory(), true); 20 | this->process()->free_memory(this->memory()); 21 | } 22 | } 23 | 24 | 25 | // EXPLICITELY DELETE COPY FUNCTIONS TO PREVENT ANY 26 | // COPYING OF THE HANDLE OBJECT 27 | 28 | // COPY CONSTRUCTOR 29 | safe_memory(const safe_memory& that) = delete; 30 | 31 | // COPY ASSIGNMENT OPERATOR 32 | safe_memory& operator= (const safe_memory& other) = delete; 33 | 34 | // MOVE CONSTRUCTOR 35 | safe_memory(safe_memory&& other) noexcept 36 | : m_process(other.m_process), m_memory(other.m_memory) 37 | { 38 | other.memory() = 0x00; // NULL OLD 39 | } 40 | 41 | // MOVE ASSIGNMENT OPERATOR 42 | safe_memory& operator= (safe_memory&& other) noexcept 43 | { 44 | this->process() = other.process(); 45 | this->memory() = other.memory(); 46 | other.memory() = 0x00; // NULL OLD 47 | return *this; 48 | } 49 | 50 | explicit operator bool() noexcept 51 | { 52 | return this->memory() != 0x00; 53 | } 54 | 55 | inline auto memory() noexcept -> std::uintptr_t& 56 | { 57 | return this->m_memory; 58 | } 59 | inline auto process() noexcept -> native::process*& 60 | { 61 | return this->m_process; 62 | } 63 | 64 | inline void detach() noexcept 65 | { 66 | this->memory() = 0x00; 67 | } 68 | 69 | private: 70 | std::uintptr_t m_memory; 71 | native::process* m_process; 72 | }; -------------------------------------------------------------------------------- /mapper/shellcode.cpp: -------------------------------------------------------------------------------- 1 | #include "shellcode.hpp" 2 | #include "maker.hpp" 3 | #include "cast.hpp" 4 | 5 | std::array shellcode::call_dllmain(std::uintptr_t image, std::uintptr_t dllmain) noexcept 6 | { 7 | // dllmain_call_x64.asm 8 | auto shellcode = maker::create_byte_array( 9 | 0x48, 0x83, 0xEC, 0x28, 0x48, 0xB9, 10 | 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 11 | 0x48, 0xC7, 0xC2, 0x01, 0x00, 0x00, 0x00, 12 | 0x4D, 0x31, 0xC0, 0x48, 0xB8, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 13 | 0xFF, 0xD0, 0x48, 0x83, 0xC4, 0x28, 0xC3); 14 | 15 | *cast::long_pointer(shellcode.data() + 0x6) = image; 16 | *cast::long_pointer(shellcode.data() + 0x1A) = dllmain; 17 | 18 | return shellcode; 19 | } 20 | 21 | std::array shellcode::hijack_dllmain(std::uintptr_t image, std::uintptr_t dllmain) noexcept 22 | { 23 | // dllmain_hijack_x64.asm 24 | auto shellcode = maker::create_byte_array(0x9C, 0x50, 0x53, 0x51, 0x52, 0x55, 0x56, 0x57, 0x41, 0x50, 0x41, 0x51, 0x41, 0x52, 0x41, 0x53, 0x41, 0x54, 0x41, 0x55, 0x41, 0x56, 0x41, 0x57, 0x48, 0x81, 0xEC, 0x00, 0x01, 0x00, 0x00, 0x48, 0xB9, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x48, 0xC7, 0xC2, 0x01, 0x00, 0x00, 0x00, 0x4D, 0x31, 0xC0, 0x48, 0xB8, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFF, 0xD0, 0x48, 0x81, 0xC4, 0x00, 0x01, 0x00, 0x00, 0x41, 0x5F, 0x41, 0x5E, 0x41, 0x5D, 0x41, 0x5C, 0x41, 0x5B, 0x41, 0x5A, 0x41, 0x59, 0x41, 0x58, 0x5F, 0x5E, 0x5D, 0x5A, 0x59, 0x5B, 0x58, 0x9D, 0x48, 0xC7, 0x05, 0x01, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0xC3, 0x90, 0x90, 0x90, 0x90, 0x90, 0x90, 0x90, 0x90); 25 | 26 | constexpr auto shadowspace_size = 0x100; 27 | 28 | *cast::int_pointer(shellcode.data() + 0x1B) = shadowspace_size; 29 | 30 | *cast::long_pointer(shellcode.data() + 0x21) = image; 31 | *cast::long_pointer(shellcode.data() + 0x35) = dllmain; 32 | 33 | *cast::int_pointer(shellcode.data() + 0x42) = shadowspace_size; 34 | 35 | return shellcode; 36 | } 37 | -------------------------------------------------------------------------------- /mapper/shellcode.hpp: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | #include 4 | 5 | namespace shellcode 6 | { 7 | constexpr std::size_t call_dllmain_size = 41; 8 | std::array call_dllmain(std::uintptr_t image, std::uintptr_t dllmain) noexcept; 9 | 10 | constexpr std::size_t hijack_dllmain_size = 114; 11 | std::array hijack_dllmain(std::uintptr_t image, std::uintptr_t dllmain) noexcept; 12 | } -------------------------------------------------------------------------------- /mapper/thread.cpp: -------------------------------------------------------------------------------- 1 | #include "thread.hpp" 2 | #include "ntdll.hpp" 3 | 4 | bool native::thread::wait(const std::uint32_t max_time) noexcept 5 | { 6 | return WaitForSingleObject(this->handle().unsafe_handle(), (max_time == 0x00) ? INFINITE : max_time) != WAIT_FAILED; 7 | } 8 | 9 | bool native::thread::resume() noexcept 10 | { 11 | // UPDATE CONTEXT 12 | if (!this->set_context()) 13 | return false; 14 | 15 | // RESUME 16 | return ResumeThread(this->handle().unsafe_handle()) != 0xFFFFFFFF; 17 | } 18 | 19 | bool native::thread::suspend() noexcept 20 | { 21 | // SUSPEND THREAD 22 | if (SuspendThread(this->handle().unsafe_handle()) == 0xFFFFFFFF) 23 | return false; 24 | 25 | // GET CONTEXT 26 | if (!this->get_context()) 27 | return false; 28 | 29 | return true; 30 | } 31 | 32 | bool native::thread::fetch() noexcept 33 | { 34 | ntdll::enumerate_threads([this](SYSTEM_THREAD_INFORMATION* thread_info) { 35 | 36 | const auto this_thread_id = cast::pointer_convert(thread_info->ClientId.UniqueThread); 37 | 38 | if (this_thread_id != this->thread_id()) 39 | return false; 40 | 41 | // FETCH 42 | this->state() = static_cast(thread_info->ThreadState); 43 | this->wait_reason() = static_cast(thread_info->WaitReason); 44 | this->start_address() = reinterpret_cast(thread_info->StartAddress); 45 | 46 | return true; 47 | }); 48 | 49 | return false; 50 | } 51 | 52 | native::thread::state_t& native::thread::state() noexcept 53 | { 54 | return this->m_state; 55 | } 56 | 57 | native::thread::wait_reason_t& native::thread::wait_reason() noexcept 58 | { 59 | return this->m_wait_reason; 60 | } 61 | 62 | std::uintptr_t& native::thread::start_address() noexcept 63 | { 64 | return this->m_start_address; 65 | } 66 | 67 | std::uint32_t& native::thread::thread_id() noexcept 68 | { 69 | return this->m_thread_id; 70 | } 71 | 72 | CONTEXT& native::thread::context() noexcept 73 | { 74 | return this->m_context; 75 | } 76 | 77 | bool native::thread::get_context() noexcept 78 | { 79 | // SPECIFY ALL REGISTERS 80 | this->m_context = CONTEXT(); 81 | this->m_context.ContextFlags = CONTEXT_FULL; 82 | 83 | return static_cast(GetThreadContext(this->handle().unsafe_handle(), &this->m_context)); 84 | } 85 | 86 | bool native::thread::set_context() noexcept 87 | { 88 | return static_cast(SetThreadContext(this->handle().unsafe_handle(), &this->m_context)); 89 | } 90 | 91 | safe_handle& native::thread::handle() noexcept 92 | { 93 | return this->m_handle; 94 | } 95 | -------------------------------------------------------------------------------- /mapper/thread.hpp: -------------------------------------------------------------------------------- 1 | #pragma once 2 | #include "safe_handle.hpp" 3 | #include "cast.hpp" 4 | 5 | #include 6 | #include 7 | 8 | namespace native 9 | { 10 | class thread 11 | { 12 | public: 13 | explicit thread(const HANDLE handle, const SYSTEM_THREAD_INFORMATION& info) noexcept : 14 | m_handle(handle), 15 | m_state(static_cast(info.ThreadState)), 16 | m_wait_reason(static_cast(info.WaitReason)), 17 | m_start_address(reinterpret_cast(info.StartAddress)), 18 | m_thread_id(cast::pointer_convert(info.ClientId.UniqueThread)) {} 19 | 20 | explicit thread(const HANDLE handle) noexcept : 21 | m_handle(handle), 22 | m_thread_id(GetThreadId(handle)) {} 23 | 24 | thread() noexcept : m_handle(nullptr) {} 25 | 26 | explicit operator bool() noexcept 27 | { 28 | return this->handle().unsafe_handle() != nullptr; 29 | } 30 | 31 | bool wait(const std::uint32_t max_time = 0) noexcept; 32 | 33 | bool resume() noexcept; 34 | bool suspend() noexcept; 35 | 36 | // DOCUMENTED DATA 37 | std::uint32_t& thread_id() noexcept; 38 | CONTEXT& context() noexcept; 39 | safe_handle& handle() noexcept; 40 | 41 | // UNDOCUMENTED DATA 42 | enum wait_reason_t : std::uint8_t 43 | { 44 | EXECUTIVE, 45 | FREE_PAGE, 46 | PAGE_IN, 47 | POOL_ALLOCATION, 48 | DELAY_EXECUTION, 49 | SUSPENDED, 50 | USER_REQUEST, 51 | WR_EXECUTIVE, 52 | WR_FREE_PAGE, 53 | WR_PAGE_IN, 54 | WR_POOL_ALLOCATION, 55 | WR_DELAY_EXECUTION, 56 | WR_SUSPENDED, 57 | WR_USER_REQUEST 58 | }; 59 | enum state_t : std::uint8_t 60 | { 61 | INITIALIZED, 62 | READY, 63 | RUNNING, 64 | STANDBY, 65 | TERMINATED, 66 | WAITING, 67 | TRANSITION, 68 | DEFERRED_READY, 69 | GATE_WAIT 70 | }; 71 | 72 | bool fetch() noexcept; 73 | state_t& state() noexcept; 74 | wait_reason_t& wait_reason() noexcept; 75 | std::uintptr_t& start_address() noexcept; 76 | 77 | 78 | private: 79 | bool get_context() noexcept; 80 | bool set_context() noexcept; 81 | 82 | state_t m_state; 83 | CONTEXT m_context; 84 | safe_handle m_handle; 85 | std::uint32_t m_thread_id; 86 | wait_reason_t m_wait_reason; 87 | std::uintptr_t m_start_address; 88 | }; 89 | } 90 | -------------------------------------------------------------------------------- /mapper/transformer.hpp: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | #include 4 | #include 5 | 6 | // USED TO TRANSFORM CHARACTERS IN STRINGS, /W4 COMPLIANT :) 7 | namespace transformer 8 | { 9 | namespace detail 10 | { 11 | inline char character_to_lower(char character) noexcept 12 | { 13 | return static_cast(tolower(character)); 14 | } 15 | inline wchar_t wide_character_to_lower(wchar_t character) noexcept 16 | { 17 | return static_cast(towlower(character)); 18 | } 19 | } 20 | 21 | inline void string_to_lower(std::string& data) noexcept 22 | { 23 | std::transform(data.begin(), data.end(), data.begin(), transformer::detail::character_to_lower); 24 | } 25 | inline void string_to_lower(std::wstring& data) noexcept 26 | { 27 | std::transform(data.begin(), data.end(), data.begin(), transformer::detail::wide_character_to_lower); 28 | } 29 | inline void string_to_lower(std::wstring& data, std::size_t size) noexcept 30 | { 31 | std::transform(data.begin(), data.begin() + size, data.begin(), transformer::detail::wide_character_to_lower); 32 | } 33 | inline void truncate(std::string& data) noexcept 34 | { 35 | data.erase(std::find(data.begin(), data.end(), '\0'), data.end()); 36 | } 37 | inline void truncate(std::wstring& data) noexcept 38 | { 39 | data.erase(std::find(data.begin(), data.end(), '\0'), data.end()); 40 | } 41 | } --------------------------------------------------------------------------------